Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if two Python functions are equal

Tags:

I am wondering how I could check to see if two functions are the same. An example would be (lambda x: x) == (lambda y: y) evaluating to true. As far as I know, Python will check to see if the functions occupy the same location in memory, but not whether they have the same operation. I know it seems impractical to have that functionality.

Another solution would be some method I can run on a function to see what it contains or how it works. So a kind of (lambda x: x).what() that would return how the method works, maybe in a dictionary or something.

I would love an answer, but I doubt it's possible.

like image 678
Hovestar Avatar asked Nov 18 '13 22:11

Hovestar


People also ask

How do you compare functions in Python?

Python - cmp() Method The cmp() is part of the python standard library which compares two integers. The result of comparison is -1 if the first integer is smaller than second and 1 if the first integer is greater than the second. If both are equal the result of cmp() is zero.

What is the == function in Python?

What is the Function of == in Python? The “==” operator is known as the equality operator. The operator will return “true” if both the operands are equal. However, it should not be confused with the “=” operator or the “is” operator.

How to check if value is equal Python?

Python strings equality can be checked using == operator or __eq__() function. Python strings are case sensitive, so these equality check methods are also case sensitive.

Can you define two functions in Python?

Functions can be defined inside a module, a class, or another function. Function defined inside a class is called a method. In this example, we define an f function in three different places.


1 Answers

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.

like image 125
Martijn Pieters Avatar answered Sep 28 '22 07:09

Martijn Pieters