Search code examples
pythonfunctionequalityfunctor

Testing function object (functor) equality, how is it evaluated? Do I use `is` or `==`?


Consider these functions:

def f():
    print("WTF?!")

def g():
    print("WTF?!")

They both do exactly the same thing, but a test of f == g still gives False. Do I assume from this that functor equality is evaluated by reference, and that there is no difference between is and ==?

Whether or not that is the case, which one is better to use (even if only stylistically)?

By the way I'm primarily interested in Python 3 (Python 3.6).

EDIT

This question is not a duplicate, I think. I understand the difference between reference equality and value equality, I just want to understand how == uses value equality (if at all) on functors.


Solution

  • Function objects have no custom __eq__ method (this method is called when comparing values with ==) so they fall back to the superclasses __eq__ method. In this case it's object.__eq__ which, indeed, just compares if they are the same object.

    So:

    >>> f == g
    False
    

    is identical (in this case) to:

    >>> f is g
    False
    

    Just in case your interested how I know that functions have no custom __eq__ method:

    >>> type(f).__eq__ is object.__eq__
    True