Documenting that inspect.Parameter.kind attributes support ordering

The following snippet is very useful:

sorted(params_set, key=(lambda param: (param.kind.value, (param.default is not param.empty)))

Its purpose is to enable an unsorted or badly-sorted iterable of Parameters to be put easily in an order that would be syntactically correct (1).

But it relies on the value attributes of the Parameter’s kinds to be integers, or at least orderable, and ordered correctly - which they are, but it’s not documented.

So it could be useful to settle it and document, as a possible minimum, that kind.value returns an orderable value and what their order is. Or to fully document it as an IntEnum. Although I wouldn’t consider documenting the integer values themselves to be a great idea.

It also seems to be the only purpose of it being an IntEnum at all, which I presume hasn’t been done randomly.

(1) unless one is a defaulted pos-only and another is a required pos-or-kw, but in that case there is no valid ordering anyway.

That’s invalid anyway, so you’re fine.

>>> def f(a, b=1, /, c): pass
  File "<stdin>", line 1
    def f(a, b=1, /, c): pass
SyntaxError: parameter without a default follows parameter with a default

_ParameterKind has been an int since at least 3.3, and probably for its entire existence. The only thing that has changed is it’s now an IntEnum instead of a different custom int.

In other words, you don’t need to access .value:

sorted(params_set, key=(lambda param: (param.kind, (param.default is not param.empty)))
1 Like

That’s great ! so how about documenting that the kinds themselves support ordering, and that their order is the one shown in the table ? That would be good enough for me.

This has been merged in gh-102296 Document that inspect.Parameter kinds support ordering by Gouvernathor · Pull Request #102297 · python/cpython · GitHub