Explain Codes LogoExplain Codes Logo

How do I look inside a Python object?

python
object-introspection
python-objects
attribute-access
Alex KataevbyAlex Kataev·Dec 30, 2024
TLDR

To explore a Python object's attributes, use dir(). To access attributes' values, use getattr():

obj = YourObject() attributes = [attr for attr in dir(obj) if not attr.startswith('__')] # exclude those pesky underscores for attr in attributes: print(f"{attr}:", getattr(obj, attr)) # {"Hola": It's me!}

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:

print(type(obj)) # Output: <class '__main__.YourObject'> — I see you!

Show me your secrets

With vars(), we skip the list comprehension in dir() to directly access the object's __dict__:

print(vars(obj)) # Output: {'attr': value, ...} — peek-a-boo!

Do you have the key?

Before rushing to access an unavailable attribute and encounter an AttributeError, first glance with hasattr():

if hasattr(obj, 'attr'): print(getattr(obj, 'attr')) # Output: value — Knock knock. Who's there? It's attr!

Can I call you?

callable() lets you know if an object can be invoked like a function. RSVP before the function call:

if callable(obj): result = obj() # Hello, this is callable!

A peek into the backstage

Review the global and local namespaces using globals() and locals(), ideal for behind-the-scenes debugging act:

print(globals()) # Global scope variables on parade! print(locals()) # Locals, roll out!

Need a tour guide?

help() is your personal tour guide for an info-rich ride through modules, classes, and functions:

help(obj) # The more you know!

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:
import inspect print(inspect.getmembers(obj)) # I know all your secrets!
  • Look at only the callable functions with inspect.isfunction() or inspect.ismethod():
methods = [m for m in inspect.getmembers(obj, predicate=inspect.isfunction)] # Function party!
  • Determine the required parameters for a function with inspect.signature():
print(inspect.signature(obj.some_method)) # Child, give me five (parameters, that is)!

Spelunking the source

If protocol allows, inspect.getsource() works like an X-ray, giving us deep insights:

print(inspect.getsource(obj.method)) # Code, open sesame!

The magical dict

Python objects carry their attributes around in a __dict__ attribute. See if you can unlock it:

print(obj.__dict__) # Whoa, look at all this stuff!