Why does `if None.__eq__(“a”)` seem to evaluate to True (but not quite)?

前端 未结 4 1636
轮回少年
轮回少年 2020-12-07 12:04

If you execute the following statement in Python 3.7, it will (from my testing) print b:

if None.__eq__(\"a\"):
    print(\"b\")
4条回答
  •  太阳男子
    2020-12-07 12:14

    Why?

    It returns a NotImplemented, yeah:

    >>> None.__eq__('a')
    NotImplemented
    >>> 
    

    But if you look at this:

    >>> bool(NotImplemented)
    True
    >>> 
    

    NotImplemented is actually a truthy value, so that's why it returns b, anything that is True will pass, anything that is False wouldn't.

    How to solve it?

    You have to check if it is True, so be more suspicious, as you see:

    >>> NotImplemented == True
    False
    >>> 
    

    So you would do:

    >>> if None.__eq__('a') == True:
        print('b')
    
    
    >>> 
    

    And as you see, it wouldn't return anything.

提交回复
热议问题