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.
The one thing you could test for is code object equality:
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 really want to know whether two functions always do the same thing for all inputs, you will have to run them both on all inputs (which will take infinite time), and also intercept all possible side effects (which is effectively impossible).
You could of course come up with some heuristics, throwing a set of different values at them that, for your application area, are very likely to generate different outputs if the functions are different. But there's obviously no general-purpose solution to that—otherwise, all unit tests would be generated automatically, saving us all a whole lot of work, right?
Conversely, you might just want to know whether two functions have the exact same implementation. For that, Martijn Pieters's answer is the obvious starting point, and possibly even the ending point (depending on whether you care about closures, globals, etc.).
But what you asked for is something different from either of these; you apparently want to look over the code manually to see "how it works":
That function already exists:
dis.dis
. When you run it on a function, it tells you how that function works. Not in a dictionary (a dictionary of what?) but in a sequence of lines of bytecode for the Python interpreter (which is a relatively simple stack machine with some higher-level stuff added on top, mostly described right there in thedis
docs).Or, even more simply, you can get the source with
inspect.getsource
.Here's what the two look like with your examples:
In the first case, you need to know enough about
dis
to realize that the(x)
, etc., are not part of the bytecode, but rather part of the function's list of local names. (This is explained as much in theinspect
docs as in thedis
docs.) In the second, you need to know enough about Python to realize that thedef
and thelambda
are defining the exact same function. So, either way, there's no way to automate this (or, really, anything much beyond Martijn's answer).