Python: check if method is static from class without instantiating

How to check if a method is static given a class, not an instance of a class. In some use cases, the instantiation of a class might have some consequences, and you might need to know if a method is static before any instantiation. Take for example the class:

class MyClass:

  def method(self):

  def static_method():

I need a function is_staticmethod that gives:

>>> is_staticmethod(MyClass, 'method')
>>> is_staticmethod(MyClass, 'static_method')

And as said before, this function should not instantiate the class. I tried to search for a question that already answered this, but got many results related to the case of class instances, which is not what I need.

>Solution :

Frist get it from the class’s namespace, then use isinstance:

def is_staticmethod(cls, m):
    return isinstance(cls.__dict__.get(m), staticmethod)

print(is_staticmethod(MyClass, 'method'))         # False
print(is_staticmethod(MyClass, 'static_method'))  # True

Leave a Reply