def keyfunc(item): value = item.get(attr, default) casted = cast(value, _type) if _type else value try: is_nan = isnan(casted) except TypeError: is_nan = False return default if is_nan else casted