python - Check if a function uses @classmethod -
tl;dr how find out whether function defined using @classmethod or same effect?
my problem
for implementing class decorator check if method takes class first argument, example achieved via
@classmethod def function(cls, ...): i found solution check @staticmethod via types module (isinstance(foo, types.unboundmethodtype) false if foo static, see here), did not find on how @classmethod
context
what trying along lines of
def class_decorator(cls): member in cls.__dict__: if (isclassmethod(getattr(cls, member))): # method setattr(cls, member, modified_method) return cls and not know how implement called isclassmethod in example
for python 2, need test both if object method, and if __self__ points class (for regular methods it'll none when retrieved class):
>>> class foo(object): ... @classmethod ... def bar(cls): ... pass ... def baz(self): ... pass ... >>> foo.baz <unbound method foo.baz> >>> foo.baz.__self__ >>> foo.baz.__self__ none true >>> foo.bar.__self__ <class '__main__.foo'> >>> foo.bar.__self__ foo true in python 3, regular methods show functions (unbound methods have been done away with).
combine inspect.ismethod() fail-safe method detect class method in both python 2 , 3:
import inspect if inspect.ismethod(cls.method) , cls.method.__self__ cls: # class method the method.__self__ attribute added in python 2.6 consistent python 3. in python 2.6 , 2.7 alias of method.im_self.
Comments
Post a Comment