Skip to content

Dynamic Object Introspection

Introspection means examining the properties of an object during runtime. IPython provides powerful and convenient tools for quickly inspecting Python objects, which is invaluable for interactive exploration and debugging.

Typing an object’s name followed by a question mark (?) displays essential information about that object, including its type, string representation, and, importantly, its docstring (if one exists).

In [1]: import numpy as np
In [2]: data = np.array([10, 20, 30])
In [3]: data?
# Output:
# Type: ndarray
# String form: [10 20 30]
# Length: 3
# File: .../numpy/core/records.py
# Docstring: ndarray(shape, dtype=float, buffer=None, offset=0, ...)
# An array object represents a multidimensional, homogeneous array...
# [... Full Docstring ...]

This works for variables, functions, classes, modules – essentially any Python object.

In [4]: def calculate(a, b=1):
...: """Calculates a simple result."""
...: return (a + 1) * b
...:
In [5]: calculate?
# Output:
# Signature: calculate(a, b=1)
# Docstring: Calculates a simple result.
# File: <ipython-input-4-...>
# Type: function

Using ?? for More Detail (Including Source Code)

Section titled “Using ?? for More Detail (Including Source Code)”

Using two question marks (??) provides even more detailed information. If the object is defined in Python (not compiled C code), ?? will also display its source code.

In [6]: calculate??
# Output:
# Signature: calculate(a, b=1)
# Docstring: Calculates a simple result.
# Source:
# def calculate(a, b=1):
# """Calculates a simple result."""
# return (a + 1) * b
# File: <ipython-input-4-...>
# Type: function

For built-in functions or objects implemented in C extensions (like many NumPy functions), ?? will typically show the same information as ? because the source code isn’t directly accessible.

You can use wildcards (*) with ? or ?? to search for names matching a pattern within the current namespace or an object’s attributes.

In [7]: import os
In [8]: os.*path*?
# Output: Lists names within the os module containing 'path'
# os.defpath
# os.get_exec_path
# os.path
# os.pathconf
# os.pathconf_names
# os.pathsep
# os.supports_unicode_filenames

Object introspection complements tab completion. While Tab helps you discover what attributes or methods an object has, ? and ?? help you understand what they do and how they are implemented.