New submission from Nick Coghlan: Currently, it's a bit annoying to sort collections containing "None" values in Python 3. While the default behaviour isn't going to change, it would be good to offer standard "none_first" and "none_last" helps (inspired by the SQL NULL FIRST and NULL LAST ordering control).
Suggested home: functools (since that is where the total_ordering class decorator already lives), but collections would also be a reasonable choice (as this feature mostly relates to sorting containers) The minimal option (suggested by Peter Otten): def none_first(v): return v is not None, v def none_last(v): return v is None, v A more complex alternative would be to provide general purpose SortsFirst and SortsLast singletons: @functools.total_ordering class _AlwaysLesser: def __eq__(self, other): return isinstance(other, _AlwaysLesser): def __lt__(self, other): return not isinstance(other, _AlwaysLesser): @functools.total_ordering class _AlwaysGreater: def __eq__(self, other): return isinstance(other, _AlwaysGreater): def __gt__(self, other): return not isinstance(other, _AlwaysGreater): SortsFirst = _AlwaysLesser() SortsLast = _AlwaysGreater() def none_first(v): return SortsFirst if v is None else v def none_last(v): return SortsLast if v is None else v The advantage of the latter more complex approach is that you can embed the SortsFirst and SortsLast values inside a tuple as part of a more complex key, whereas the simple solution only handles the case where the entire value is None. (Inspired by Chris Withers's python-dev thread: https://mail.python.org/pipermail/python-dev/2014-February/132332.html) ---------- messages: 211251 nosy: ncoghlan priority: normal severity: normal status: open title: Add sorting helpers for collections containing None values type: enhancement versions: Python 3.5 _______________________________________ Python tracker <rep...@bugs.python.org> <http://bugs.python.org/issue20630> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com