Python: max/min builtin functions depend on parameter order

后端 未结 3 2171
半阙折子戏
半阙折子戏 2020-11-29 07:51

max(float(\'nan\'), 1) evaluates to nan

max(1, float(\'nan\')) evaluates to 1

Is it the intended behavior?


Thanks for

3条回答
  •  既然无缘
    2020-11-29 08:43

    I haven't seen this before, but it makes sense. Notice that nan is a very weird object:

    >>> x = float('nan')
    >>> x == x
    False
    >>> x > 1
    False
    >>> x < 1
    False
    

    I would say that the behaviour of max is undefined in this case -- what answer would you expect? The only sensible behaviour is to assume that the operations are antisymmetric.


    Notice that you can reproduce this behaviour by making a broken class:

    >>> class Broken(object):
    ...     __le__ = __ge__ = __eq__ = __lt__ = __gt__ = __ne__ =
    ...     lambda self, other: False
    ...
    >>> x = Broken()
    >>> x == x
    False
    >>> x < 1
    False
    >>> x > 1
    False
    >>> max(x, 1)
    <__main__.Broken object at 0x024B5B50>
    >>> max(1, x)
    1
    

提交回复
热议问题