Explain Codes LogoExplain Codes Logo

How do I get a list of methods in a Python class?

python
introspection
methods
python-3
Nikita BarsukovbyNikita BarsukovΒ·Dec 26, 2024
⚑TLDR

To quickly get a list of non-special methods from a Python class, you can use the inspect module as follows:

import inspect class MyClass: def chicken_nuggets(self): pass # πŸ” def french_fries(self): pass # 🍟 methods = [m[0] for m in inspect.getmembers(MyClass, predicate=inspect.isfunction)] print(methods) # πŸ“»

Output:

['chicken_nuggets', 'french_fries']

Class versus Instance Methods

Class and instance methods are plotted differently by inspect.getmembers(). To list instance methods, pass an instance:

instance = MyClass() bit_of_this = [m[0] for m in inspect.getmembers(instance, predicate=inspect.ismethod)]

For listing class methods, pass the class itself:

bit_of_that = [m[0] for m in inspect.getmembers(MyClass, predicate=inspect.isfunction)]

Heads-up from Python 3: inspect.ismethod metamorphosed!

Private and Special Methods

To find all attributes, including the private and "dunder" methods, use dir().

not_a_secret = [method for method in dir(MyClass) if callable(getattr(MyClass, method))]

To exclude introspected ones, those starting with __, use list comprehension:

nosey_parker = [method for method in dir(MyClass) if callable(getattr(MyClass, method)) and not method.startswith("__")]

Static Methods, Anyone?

Static methods, just like weird cousins, behave differently. Here's how you nab 'em:

static_methods = [m[0] for m in inspect.getmembers(MyClass, predicate=inspect.isfunction) if isinstance(MyClass.__dict__.get(m[0]), staticmethod)]

Docstring Comprehension

To understand what secretive methods do, peek into the docstring with inspect.getdoc(). It feels like unveiling secrets.

for method in methods: print(f"Method: {method}\nDoc: {inspect.getdoc(getattr(MyClass, method))}\n") # Tells πŸ•΅οΈ

Runtime Check

While introspection smoothly handles runtime attributes, remember, it's not free. It can cause a performance hit, so don't overdo it.

Need help?

Python's interactive help system is like an info desk. Use help() and interrogate your class:

help(MyClass) # Knock-knock, Python speaking 🐍