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.
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 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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With