[FIXED] python iterate static method for class

Issue

import inspect


class Wrapper:
    @staticmethod
    def a():
        pass

    @staticmethod
    def b():
        pass


# print(inspect.getmembers(Wrapper, lambda x: inspect.isfunction(x)))
# print(inspect.getmembers(Wrapper, lambda x: inspect.ismethod(x)))

to use Wrapper as a module of static methods, how can I obtain a list of [a, b].


Solution

inspect.getmembers internally uses getattr to get the members in the class, and during this process, staticmethod will be converted into the wrapped function, thus losing information.

If you want to get all the functions wrapped by staticmethod, the easiest way is to traverse the class dictionary and check it with isinstance:

>>> class Wrapper:
...     @staticmethod
...     def a():
...         pass
...     @staticmethod
...     def b():
...         pass
...
>>> [member.__func__
...  for member in vars(Wrapper).values()
...  if isinstance(member, staticmethod)]
[<function Wrapper.a at 0x79882bd160>,
 <function Wrapper.b at 0x79882bd1f0>]

This won't get the static methods in the base class. If necessary, you have to traverse each base class yourself. One possible method is as follows:

{name: member.__func__
 for base in reversed(Wrapper.mro()[:-1])
 for name, member in vars(base).items()
 if isinstance(member, staticmethod)}


Answered By - Mechanic Pig
Answer Checked By - Robin (Python.Easybugfix Admin)

Related Posts

Post a Comment