How can I tell if a class instance method and function are the same?
I have a simple class that uses a decorator:
@decorate_class
class Hello:
@decorate_func
def world(self):
return
And these are my decorators:
# A global variable
global_func = None
def decorate_func(func):
global_func = func
return func
def decorate_class(clazz):
print clazz.__dict__["world"] == global_func
return clazz
The above returns False, possible because type(func) in decorate_func is function, but in decorate_class it is instancemethod. But printing both of them gives me:
<function world at 0x7f490e59ce60>
As in, the same memory address. How do I compare them to know that they are the same function? Is comparing by the memory address safe (and correct)?
Your problem here is actually your use of
global_func.If you change
decorate_classto:You’ll see that
global_funcisNone.To fix this, explicitly declare
global_funcasglobalindecorate_func:And everything will work.
This is (basically) because Python assumes that, if you assign to a variable in a function, that variable is assumed to be local to that function, unless it is explicitly declared to be global.