How do I look inside a Python object?
To explore a Python object's attributes, use dir()
. To access attributes' values, use getattr()
:
This technique strips away special methods and focuses on user-defined properties to provide a bird's-eye view of the object's structure.
Deep dive into object introspection
Starting with a quick snapshot from dir()
and getattr()
, let's dive deeper into available tools for introspection.
What's your type?
Using type()
identifies the class of an object, helping us predict what operations it supports:
Show me your secrets
With vars()
, we skip the list comprehension in dir()
to directly access the object's __dict__
:
Do you have the key?
Before rushing to access an unavailable attribute and encounter an AttributeError, first glance with hasattr()
:
Can I call you?
callable()
lets you know if an object can be invoked like a function. RSVP before the function call:
A peek into the backstage
Review the global and local namespaces using globals()
and locals()
, ideal for behind-the-scenes debugging act:
Need a tour guide?
help()
is your personal tour guide for an info-rich ride through modules, classes, and functions:
The advanced reconnaissance with inspect module
The inspect
module is the special spy gadget for those wishing to go even deeper. This tool helps you discover the specific functions and even the source code of an object:
inspect.getmembers()
helps find all the members of an object:
- Look at only the callable functions with
inspect.isfunction()
orinspect.ismethod()
:
- Determine the required parameters for a function with
inspect.signature()
:
Spelunking the source
If protocol allows, inspect.getsource()
works like an X-ray, giving us deep insights:
The magical dict
Python objects carry their attributes around in a __dict__
attribute. See if you can unlock it:
Was this article helpful?