Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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):
    pass

  @staticmethod
  def static_method():
    pass

I need a function is_staticmethod that gives:

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading