Finding what methods a Python object has
Quickly identify an object's available methods in Python with:
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:
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:
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:
We just found all the methods in the math module! Who knew that math could be so cooperative?
Was this article helpful?