Weilory
Weilory

Reputation: 3121

python iterate static method for class

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].

Upvotes: 0

Views: 142

Answers (1)

Mechanic Pig
Mechanic Pig

Reputation: 7736

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)}

Upvotes: 2

Related Questions