1

I want to find out all classmethods of class Something below by using code reflection. With all classmethods i mean all methods which are decorated with @classmethod. I don't actually know if that is the same.

class Something:
    @classmethod
    def a(cls):
        print('a')

    @staticmethod
    def b(cls):
        print('b')

    def c(self):
        print('c')

So in this case I expect getting a list which contains only 'a':

get_classmethod_names(Something) == ['a']
1
  • I will use the looked up names to feed an argparser and then use the found out names to call the function. You still may ask why and maybe rightfully so, because it looks like a stupid design decision. However, the code which i'm using reflection on is like it is and not subject to change. Commented Jan 8, 2020 at 12:29

1 Answer 1

3

This can be as simple as iterating through the classes attributes and checking for classmethod objects:

In [1]: class Something:
   ...:     @classmethod
   ...:     def a(cls):
   ...:         print('a')
   ...:
   ...:     @staticmethod
   ...:     def b(cls):
   ...:         print('b')
   ...:
   ...:     def c(self):
   ...:         print('c')
   ...:

In [2]: [attr for attr, obj in vars(Something).items() if isinstance(obj, classmethod)]
Out[2]: ['a']

Note, if you care about inherited classmethods, then you have to check it for every class in your classe's method-resolution order, so:

In [3]: class BaseSomething:
   ...:     @classmethod
   ...:     def u(cls):
   ...:         print('u')
   ...:
   ...: class Something(BaseSomething):
   ...:     @classmethod
   ...:     def a(cls):
   ...:         print('a')
   ...:
   ...:     @staticmethod
   ...:     def b(cls):
   ...:         print('b')
   ...:
   ...:     def c(self):
   ...:         print('c')
   ...:

In [4]: Something.mro()
Out[4]: [__main__.Something, __main__.BaseSomething, object]

In [5]: [
   ...:     attr
   ...:     for cls in Something.mro()
   ...:     for attr, obj in vars(cls).items()
   ...:     if isinstance(obj, classmethod)
   ...: ]
Out[5]: ['a', 'u']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.