Check if two Python functions are equal

The one thing you could test for is code object equality:

>>> x = lambda x: x
>>> y = lambda y: y
>>> x.__code__.co_code
'|\x00\x00S'
>>> x.__code__.co_code == y.__code__.co_code
True

Here the bytecode for both functions is the same. You’ll perhaps need to verify more aspects of the code objects (constants and closures spring to mind), but equal bytecode should equal the same execution path.

There are of course ways to create functions that return the same value for the same input, but with different bytecode; there are always more ways to skin a fish.

Leave a Comment