I've been using my_function.__code__.co_code
to check whether two functions have the same source code or not (as suggested e.g. here). However, it turns out that this doesn't do exactly what I was expecting. Let's take this example.
def f(a, b):
return a
return a
def g(a, b):
return a
if __name__ == '__main__':
print(f.__code__.co_code)
print(g.__code__.co_code)
print("f.__code__.co_code == g.__code__.co_code?",
f.__code__.co_code == g.__code__.co_code)
The functions are logically equivalent, but they have different code, so I was expecting f.__code__.co_code == g.__code__.co_code
to return False
, but it returns True
. This is probably because Python understands that f
can be simplified to g
.
However, would there be a way to stop Python from doing that, i.e. if the functions really contain different code (although they may be logically equivalent), f.__code__.co_code == g.__code__.co_code
returns False
? Or would there be any solution to my problem?
Essentially, I am looking for a function/property that would return a (preferably hashable) representation of a function, which, if compared to the representation of another function, would be different, unless the functions contain exactly the same code. It's fine that the functions have different names, i.e. if they have different names, but the same code, it should return True
(the functions are equal).
f is g
is not what I am looking for. It would return False
for these functions
def f(a, b):
return a
def g(a, b):
return a
However, they contain the same code!
I would also like to note that I want spaces and comments to be ignored. So, the following two functions would be equal
def f( a , b):
"""Good job... hm, it was a good day..."""
return a
# NICE
def g(a, b ):
# HELLLOOOOOOO
return a