Search code examples
pythonequality

Is it a good idea to use "is" to check which function is contained in a variable?


I have a variable that contains a function.

def foo(x):
    return x + 42

def bar(x):
    return x - 42

my_var = foo

I want to check if that function is a certain function. Should I use is or ==?

my_var == foo
my_var == bar

and

my_var is foo
my_var is bar

both return what I expect.


Solution

  • No, you should use ==.

    A good rule of thumb is only use is when doing is None or is not None and nowhere else. In this case, comparing functions with is works, but if you try to compare a method of an instance of a class with itself you'll get False (even on the same instance), whereas comparing with == returns what you expect:

    >>> class A:
    ...     def my_method(self):
    ...         pass
    ... 
    >>> a = A()
    >>> a.my_method is a.my_method
    False
    >>> a.my_method == a.my_method
    True
    

    Better to avoid having to remember this and always compare functions with ==.

    See this question: Why don't methods have reference equality?