Python objects
object inspection
Python programming
introspection
object attributes

How do I look inside a Python object?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Python has strong introspection features, so you can inspect object attributes, methods, types, and source information at runtime. This is useful when debugging unfamiliar libraries or exploring dynamic APIs. The key is choosing the right inspection tool for the specific question you are trying to answer.

Start with type, dir, and vars

Use basic built-ins first.

python
1class User:
2    def __init__(self, name):
3        self.name = name
4
5    def greet(self):
6        return f"Hi {self.name}"
7
8u = User("Lina")
9print(type(u))
10print(dir(u)[:10])
11print(vars(u))
  • type tells you the class.
  • dir lists accessible names.
  • vars returns instance dictionary when available.

Inspect Instance Attributes and Class Attributes

Attributes can live on the instance or class.

python
1class Config:
2    app_name = "demo"
3
4    def __init__(self):
5        self.debug = True
6
7c = Config()
8print(c.__dict__)          # instance fields
9print(Config.__dict__.keys())  # class-level attributes and methods

Understanding this distinction helps explain shadowing and method lookup behavior.

Use inspect for Deeper Introspection

The inspect module can reveal signatures, docs, and source.

python
1import inspect
2
3def add(a: int, b: int = 0) -> int:
4    """Return sum."""
5    return a + b
6
7print(inspect.signature(add))
8print(inspect.getdoc(add))
9print(inspect.getsource(add))

For third-party packages, source may be unavailable in some environments, but signatures and docs are often still accessible.

Check Available Methods and Their Callability

When object APIs are unclear, list callable members.

python
1import inspect
2
3methods = [
4    (name, member)
5    for name, member in inspect.getmembers(u)
6    if callable(member) and not name.startswith("__")
7]
8
9for name, _ in methods:
10    print(name)

This helps discover capabilities without reading full documentation first.

Pretty Print Nested Structures

Objects frequently contain nested dictionaries and lists. Pretty printing improves readability.

python
1from pprint import pprint
2
3payload = {
4    "user": {"id": 1, "name": "Lina"},
5    "roles": ["admin", "editor"],
6}
7
8pprint(payload)

For dataclasses, convert to dictionaries first.

python
1from dataclasses import dataclass, asdict
2
3@dataclass
4class Point:
5    x: int
6    y: int
7
8pprint(asdict(Point(3, 4)))

Interactive Tips in REPL and Notebooks

In interactive sessions:

  • help(obj) shows docs and methods.
  • Tab completion reveals available names.
  • obj.__class__.__mro__ shows inheritance chain.
python
print(u.__class__.__mro__)

These shortcuts speed up library exploration.

Safe Introspection Practices

Some properties execute code when accessed. Prefer non-invasive inspection first.

  • Start with dir and inspect.getmembers filters.
  • Avoid blindly evaluating every attribute.
  • Wrap inspection in try blocks for unstable objects.
python
1for name in dir(u):
2    if name.startswith("__"):
3        continue
4    try:
5        value = getattr(u, name)
6        print(name, type(value))
7    except Exception as e:
8        print(name, "error", e)

This avoids debugger crashes when objects contain side-effecting descriptors.

Inspect Object Source and Inheritance

When behavior is inherited, inspect class hierarchy and method resolution order.

python
1import inspect
2
3print(inspect.getsource(User))
4print(User.__mro__)

This clarifies where methods are defined and which implementation executes first in complex class trees.

Inspect Dictionary-Like and Slot-Based Objects

Not all objects expose __dict__. Slot-based classes need different handling.

python
1class SlotUser(object):
2    __slots__ = ("name",)
3
4s = SlotUser()
5s.name = "Mira"
6
7print(hasattr(s, "__dict__"))  # often False
8print(s.name)

Knowing this distinction prevents false assumptions during debugging utilities.

Common Pitfalls

  • Assuming dir output equals only instance attributes.
  • Accessing properties that trigger expensive work or side effects.
  • Ignoring inheritance when searching for method definitions.
  • Treating dynamically generated attributes as static API contracts.
  • Inspecting objects in production paths with heavy logging overhead.

Summary

  • Python introspection starts with type, dir, and vars.
  • Use inspect for signatures, docs, and source details.
  • Distinguish instance and class attribute storage.
  • Use pretty printing and dataclass helpers for nested data.
  • Inspect defensively to avoid side effects during debugging.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.