Python
object methods
programming tips
Python tutorial
code inspection

Finding what methods a Python object has

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

When debugging unfamiliar Python objects, you often need to discover available methods quickly. Python gives strong introspection tools, but each tool answers a different question. Choosing the right one helps you inspect APIs safely and avoid noisy output.

Start with dir for Fast Surface Discovery

dir(obj) lists attribute names, including methods and data attributes. It is the fastest first step when exploring a new object.

python
1class User:
2    def __init__(self, name):
3        self.name = name
4
5    def greet(self):
6        return f"Hello, {self.name}"
7
8u = User("Ava")
9print(dir(u))

This output includes inherited members too. That is useful, but can be verbose.

Filter to Callable Methods with inspect

To get only methods, use inspect.getmembers with callable. This gives pairs of method names and method objects.

python
1import inspect
2
3
4def list_methods(obj):
5    return [name for name, member in inspect.getmembers(obj, predicate=callable)]
6
7print(list_methods(u))

For class-level inspection, pass the class instead of an instance. This helps when object construction has side effects and you want to avoid calling constructors.

Exclude Dunder Methods for Cleaner Results

Special methods such as __repr__ and __init__ are useful but can clutter exploratory output. Filter them when you only want user-defined API methods.

python
1def list_public_methods(obj):
2    methods = []
3    for name, member in inspect.getmembers(obj, predicate=callable):
4        if not name.startswith("_"):
5            methods.append(name)
6    return methods
7
8print(list_public_methods(u))

This pattern is practical for generating docs or validating plugin interfaces.

Get Signatures and Docstrings

Method names alone are often not enough. Use inspect.signature and inspect.getdoc to understand call patterns and usage.

python
1import inspect
2
3for name, member in inspect.getmembers(User, predicate=callable):
4    if name.startswith("_"):
5        continue
6    sig = inspect.signature(member)
7    doc = inspect.getdoc(member) or "No docstring"
8    print(f"{name}{sig}")
9    print(f"  doc: {doc}")

This gives structured information suitable for diagnostics, runtime validation, or dynamic wrappers.

Runtime Safety Considerations

Introspection should avoid triggering expensive properties or side effects. Prefer class-level inspection if instance attributes compute values lazily. In plugin systems, inspect only trusted modules and avoid executing arbitrary code during discovery.

For large systems, wrap introspection in utility functions and cache results to reduce repeated reflection overhead.

Practical Introspection Utility

For larger projects, create one reusable introspection helper that can print public methods, signatures, and originating class. This saves time when debugging third-party clients or dynamically loaded plugins. Add filters for inherited members so you can focus on methods declared by the target type only when needed. Another useful option is exporting method metadata as JSON for automated documentation tooling. This keeps exploratory debugging and documentation generation aligned. In security-sensitive contexts, run introspection only on trusted objects and modules because reflection details can expose implementation internals. Finally, include tests for your utility so upgrades to Python versions do not silently change output shape.

python
1import inspect
2
3def method_catalog(obj):
4    catalog = []
5    for name, member in inspect.getmembers(obj, predicate=callable):
6        if name.startswith("_"):
7            continue
8        sig = str(inspect.signature(member))
9        catalog.append({"name": name, "signature": sig})
10    return catalog
11
12print(method_catalog(User("Ava")))

Verification Checklist

Validate introspection helpers against built-in types, user-defined classes, and objects with dynamic attributes. Confirm output remains stable across supported Python versions so debugging scripts remain trustworthy.

Common Pitfalls

  • Assuming dir returns methods only. It includes non-callable attributes too.
  • Forgetting inherited methods when analyzing behavior.
  • Triggering side effects by inspecting live instances with complex descriptors.
  • Ignoring method signatures and relying only on names.

For command-line diagnostics, provide an option to output plain text or JSON so both humans and automation can consume introspection results.

Summary

  • Use dir for fast top-level discovery.
  • Use inspect.getmembers with callable to list methods precisely.
  • Filter dunder methods when focusing on public APIs.
  • Inspect signatures and docstrings for practical usage details.
  • Build reusable introspection helpers for consistent debugging.

Course illustration
Course illustration

All Rights Reserved.