Python
programming
object attributes
duplicate question
coding help

List attributes of an object

Master System Design with Codemia

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

Introduction

Listing object attributes in Python is useful for debugging, introspection, and dynamic tooling. The right method depends on whether you want instance data, methods, or full class-level metadata. Using dir, vars, and inspect intentionally gives accurate and readable introspection output.

Core Sections

Quick Attribute Listing with dir

dir(obj) returns attribute names available on the object, including inherited members.

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

This is broad and useful for exploration, but includes magic names and methods.

Instance Attributes with vars or __dict__

If you only want instance data fields, use vars or obj.__dict__.

python
print(vars(u))        # {'name': 'Alice'}
print(u.__dict__)     # {'name': 'Alice'}

This is the cleanest path for serialization-like debugging.

Filter Public and Callable Members

For better readability, filter names and values explicitly.

python
1def public_members(obj):
2    return [name for name in dir(obj) if not name.startswith("_")]
3
4print(public_members(u))
5
6methods = [name for name in dir(u) if callable(getattr(u, name)) and not name.startswith("_")]
7print(methods)

This separates methods from data members for clearer output.

Use inspect for Richer Metadata

The inspect module helps discover functions, signatures, and class details.

python
1import inspect
2
3for name, member in inspect.getmembers(User, predicate=inspect.isfunction):
4    print(name, inspect.signature(member))

This is useful for plugin systems and auto-documentation tools.

Dataclasses and Typed Models

For dataclasses, prefer dataclasses.fields to inspect declared model fields reliably.

python
1from dataclasses import dataclass, fields
2
3@dataclass
4class Product:
5    id: int
6    name: str
7
8for f in fields(Product):
9    print(f.name, f.type)

Framework-specific models often provide their own metadata APIs, which are safer than raw introspection.

Security and Privacy Considerations

Do not dump full attributes in production logs for sensitive objects. Attributes may include tokens, personal data, or internal secrets. Build allowlists when introspection output is user-visible or exported.

For debugging endpoints, redact values and gate access behind administrative controls.

Practical Debug Utility for Safe Introspection

In production support tools, a safe introspection helper can reveal object state without exposing sensitive fields. Build a reusable filter with allowlist and optional depth limits.

python
1def safe_attrs(obj, allow=None):
2    allow = set(allow or [])
3    raw = vars(obj) if hasattr(obj, "__dict__") else {}
4    if allow:
5        return {k: raw.get(k) for k in allow if k in raw}
6    return raw
7
8class Session:
9    def __init__(self, user_id, token):
10        self.user_id = user_id
11        self.token = token
12
13s = Session("u-1", "secret-token")
14print(safe_attrs(s, allow=["user_id"]))

This keeps diagnostics useful while reducing leakage risk.

Introspection in Dynamic Frameworks

Framework objects often override attribute resolution with descriptors or properties. In those cases, dir may show names whose values trigger lazy loading or side effects. Prefer framework APIs for metadata when available, and avoid evaluating arbitrary attributes during debug output generation.

If reflection is required, catch exceptions around getattr and mark problematic attributes rather than failing the whole inspection routine.

When building admin tools, present introspection data with clear labels for class-level and instance-level values. This reduces misinterpretation and avoids accidental edits based on incomplete context.

For maintainability, keep introspection utilities small and well-tested so behavior stays predictable across Python upgrades and framework changes.

Common Pitfalls

  • Using dir output directly and assuming every name is instance data.
  • Logging entire __dict__ for sensitive domain objects.
  • Forgetting inherited attributes when introspection appears incomplete.
  • Treating framework-generated attributes as stable public API.
  • Relying on reflection-heavy code paths in performance-critical loops.

Summary

  • Use dir for broad exploration of available attributes.
  • Use vars or __dict__ for instance field inspection.
  • Use inspect for method and signature metadata.
  • Prefer framework or dataclass metadata APIs when available.
  • Apply privacy and security controls to introspection outputs.

Course illustration
Course illustration

All Rights Reserved.