python函数比较dunders的用法

Python functions have comparison dunders (see print out below). But they are NotImplemented. Fair enough. But what is their intended use, and how does one go about using them? When I assign a callable to func.__gt__, I'm not seeing be called when I do func < other_func.

范例程式码

I could see the use of having (foo > bar) being a function equivalent to lambda x: foo(x) > bar(x), but equally (and arguably more useful), it could be used to construct a pipeline.

例如,我们可以

def composeable(func):
    func.__gt__ = lambda g: lambda x: g(f(x))
    func.__lt__ = lambda g: lambda x: f(g(x))
    return func

可以用作

>>> def composeable(func):
...     func.__gt__ = lambda g: lambda x: g(f(x))
...     func.__lt__ = lambda g: lambda x: f(g(x))
...     return func
...
>>> @composeable
... def f(x):
...     return x + 2
...
>>> def g(x):
...     return x * 10
...
>>> h = f.__gt__(g)
>>> assert h(3) == 50  # (3 + 2) * 10
>>> h = f.__lt__(g)
>>> assert h(3) == 32  # (3 * 10) + 2

然而,越来越好奇,这行不通:

>>> h = f > g
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'function' and 'function'

Notes: The callable NotImplemented function dunders.

__eq__: NotImplemented
__ge__: NotImplemented
__gt__: NotImplemented
__le__: NotImplemented
__lt__: NotImplemented
__ne__: NotImplemented

生成上述打印输出的代码:

from inspect import signature

def f(x): ...

for aname in dir(f):
    attr = getattr(f, aname)
    if callable(attr):
        try:
            x = attr(*len(signature(attr).parameters) * [''])
            if x is NotImplemented:
                print(f"{aname}: NotImplemented")
        except Exception as e:
            pass