What is the difference between “ is None ” and “ ==None ”

后端 未结 5 918
无人共我
无人共我 2020-11-22 11:33

I recently came across this syntax, I am unaware of the difference.

I would appreciate it if someone could tell me the difference.

5条回答
  •  心在旅途
    2020-11-22 11:41

    It depends on what you are comparing to None. Some classes have custom comparison methods that treat == None differently from is None.

    In particular the output of a == None does not even have to be boolean !! - a frequent cause of bugs.

    For a specific example take a numpy array where the == comparison is implemented elementwise:

    import numpy as np
    a = np.zeros(3) # now a is array([0., 0., 0.])
    a == None #compares elementwise, outputs array([False, False, False]), i.e. not boolean!!!
    a is None #compares object to object, outputs False
    

提交回复
热议问题