Python3: check if method is static
class A: def f(self): return 'this is f' @staticmethod def g(): return 'this is g'print(type(A.__dict__['g']))print(type(A.g))<class 'staticmethod'><class 'function'>
I needed this solution and wrote the following based on the answer from @root
def is_method_static(cls, method_name): # http://stackoverflow.com/questions/14187973/python3-check-if-method-is-static for c in cls.mro(): if method_name in c.__dict__: return isinstance(c.__dict__[method_name], staticmethod) raise RuntimeError("Unable to find %s in %s" % (method_name, cls.__name__))
For Python 3.2 or newer, use inspect.getattr_static()
to retrieve the attribute without invoking the descriptor protocol:
Retrieve attributes without triggering dynamic lookup via the descriptor protocol,
__getattr__()
or__getattribute__()
.
Use isinstance(..., staticmethod)
on the result:
>>> from inspect import getattr_static>>> isinstance(getattr_static(A, 'g'), staticmethod)True
The function can handle both instances and classes, and will scan the full class hierarchy for you:
>>> class B(A): pass...>>> isinstance(getattr_static(B, 'g'), staticmethod) # inheritedTrue>>> isinstance(getattr_static(B(), 'g'), staticmethod) # instance, inheritedTrue