2

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.

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103

3 Answers3

4

They are the same thing for a function object. The == operator calls the __eq__ function to perform the comparison. The function object does not define an __eq__ method:

>>> def foo():
...   pass
... 
>>> foo.__eq__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute '__eq__'

Therefore the interpreter uses the default implementation in PyObject:

res = (v == w) ? Py_True : Py_False;

which is basically a pointer comparison, essentially the same as is.

Selcuk
  • 57,004
  • 12
  • 102
  • 110
1

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?

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
0

Is checks for the identity of an object. If you assign foo to myvar, then an alias is created and they both have the same id (in the case of functions at least).

Checking 2 functions for equivalence from a mathematical standpoint entails checking the equivalence of the domains and codomains of both functions.

So is is better.

Xero Smith
  • 1,968
  • 1
  • 14
  • 19