I’m having a little problem decorating a static method in Python. I think the following code best represents my problem:
def decorator(func):
print callable(func)
return func
class Foo():
@decorator
@staticmethod
def bar():
return
# outputs False
print callable(Foo.bar)
# outputs True
This seems to be a bug. I imagine it arises because when the method Foo.bar is passed to the decorator, it is a function, not a method. That is the only reason I can see for it not being callable, for if we decorate a standard function, it is not callable, as shown below.
@staticmethod
def function():
return
print callable(function)
# outputs False
So is this a true bug in implementation of the staticmethod decorator, and/or are there any simple workarounds? I did think of writing a decorator to asign a __call__ attribute, but I don’t know how callable is implemented, so I can’t gauge the sucess of such a method.
Methods are functions. But
staticmethodobjects aren’t. They are descriptors, so there’s extra magic that gives you a callable when you access it asCls.static_method, but this magic can’t hide anything when you use (i.e. pass to decorator)static_methodinside the body ofCls. You can’t really hack your way around this, at least not cleanly. A much simpler solution is reordering the decorators such thatstaticmethodget applied last – i.e. put it at the top, above all other decorators.