Explain Codes LogoExplain Codes Logo

Finding what methods a Python object has

python
introspection
error-handling
methods
Alex KataevbyAlex Kataev·Aug 17, 2024
TLDR

Quickly identify an object's available methods in Python with:

obj = "example string" print([m for m in dir(obj) if callable(getattr(obj, m))])

This tidbit lists all methods of obj using dir() to inventory attributes and callable() to filter steps that are, indeed, methods.

In-depth exploration

Error handling using try-except

While dealing with attributes of Python objects, it is common to encounter those that may cause AttributeError when called using getattr(). Ensure this error doesn't put a wrench in the works by implementing a try-except block:

obj = "example string" methods = [] for attr_name in dir(obj): try: attr = getattr(obj, attr_name) if callable(attr): methods.append((attr_name, attr.__doc__)) except AttributeError as e: print(f"Looks like {attr_name} threw us a curveball. Moving on...") continue for method, doc in methods: print(f"{method}: {doc or 'Crickets... No docstring here.'}")

Now we're not only fetching the methods, but also their docstrings (where available), providing an encompassing comment on each method's function.

Mastering attribute checks with hasattr()

Avoid diving headfirst into an empty pool by checking if certain methods exist in your object using hasattr(obj, 'method').

Python introspection like a pro!

Sometimes out-of-box functions just don't cut it. Fear not! Python sports the awesome inspect module perfect for the more complex introspection task:

import inspect obj = "example string" methods = inspect.getmembers(obj, predicate=inspect.isroutine)

This snippet will return the object's methods, even the ones it has inherited from its ancestors.

Dealing with different object types

Not all objects are of the same type, but they can still tell you their methods. Here's how to wrangle with classes, functions, and modules:

import math math_methods = [m for m in dir(math) if callable(getattr(math, m))]

We just found all the methods in the math module! Who knew that math could be so cooperative?