🧱 Python Object-Oriented Programming (OOP)
Estimated reading: 4 minutes 291 views

Python Reflection – Use getattr, setattr, dir and More

Introduction – Why Use Reflection in Python?

In dynamic languages like Python, reflection allows you to examine, modify, and invoke objects and their attributes at runtime—without knowing their names at coding time.

Reflection is powerful when you want to:

  • Dynamically access attributes and methods
  • Build flexible frameworks, serializers, or ORMs
  • Write generic and reusable code

In this guide, you’ll learn:

  • What reflection is in Python
  • How to use functions like getattr, setattr, hasattr, type, dir
  • Real-world examples (e.g., API clients, data validation)
  • Best practices and pitfalls

What Is Reflection in Python?

Reflection is the ability of a program to inspect and manipulate its own structure (variables, methods, classes) at runtime.

Python supports reflection using built-in functions and introspection tools.


Key Reflection Functions in Python

FunctionPurpose
getattr()Get the value of an attribute
setattr()Set the value of an attribute
hasattr()Check if an object has an attribute
delattr()Delete an attribute
type()Get the type of an object
isinstance()Check class inheritance
callable()Check if an object is callable
dir()List all attributes and methods of an object

Example – Using getattr, setattr, hasattr

class Person:
    def __init__(self):
        self.name = "Alice"
    def greet(self):
        return f"Hello, {self.name}"

p = Person()

# Reflection in action
print(getattr(p, 'name'))          # Alice
print(hasattr(p, 'greet'))         # True
setattr(p, 'name', 'Bob')          
print(p.greet())                   # Hello, Bob

Use Case – Dynamic Method Calling

class Calculator:
    def add(self, a, b): return a + b
    def subtract(self, a, b): return a - b

calc = Calculator()

method_name = 'add'
if hasattr(calc, method_name):
    func = getattr(calc, method_name)
    print(func(5, 3))  # 8

Dynamically calling a method using its name as a string.


Inspecting Class Metadata with type and dir

class Example:
    def __init__(self):
        self.x = 10
    def method(self): pass

e = Example()
print(type(e))        # <class '__main__.Example'>
print(dir(e))         # Lists all attributes and methods

Real-World Application – Object Serializer

def serialize(obj):
    return {key: getattr(obj, key) for key in dir(obj) if not key.startswith('_') and not callable(getattr(obj, key))}

class Product:
    def __init__(self):
        self.name = "Pen"
        self.price = 10

p = Product()
print(serialize(p))  # {'name': 'Pen', 'price': 10}

Use reflection to build a generic serializer.


Reflection vs Introspection

FeatureReflectionIntrospection
PurposeInspect and modify runtime behaviorInspect only (non-modifying)
Toolsgetattr(), setattr()type(), dir(), isinstance()
Example UseDynamic method calls, attribute settingType checking, debugging

Best Practices

Do This Avoid This
Use reflection for framework designOverusing it for basic tasks
Always check with hasattr() before getattr()Risk of AttributeError otherwise
Avoid using reflection when unnecessaryCan hurt readability and performance
Combine with decorators for dynamic behaviorUsing in performance-critical loops

Summary – Recap & Next Steps

Reflection in Python enables you to dynamically explore and interact with objects at runtime, making it ideal for frameworks, APIs, testing, and dynamic execution.

Key Takeaways:

  • Use getattr, setattr, hasattr, and dir() to interact with objects
  • Reflection is powerful but should be used judiciously
  • Helps with dynamic dispatch, serialization, and generic programming
  • May reduce performance and clarity if overused

Real-World Relevance:
Reflection powers ORMs (like SQLAlchemy), testing frameworks (like pytest), and dynamic APIs.


FAQ – Python Reflection

What is reflection in Python?

Reflection lets you inspect and modify objects, classes, and methods at runtime.

How do I get the value of an attribute by name?

Use getattr(obj, 'attr_name').

How do I check if a method exists before calling it?

Use:

if hasattr(obj, 'method_name'):
    getattr(obj, 'method_name')()

Can reflection hurt performance?

Yes, especially if used in tight loops or frequently accessed logic.

Is Python’s reflection the same as Java’s?

Similar in concept, but Python uses dynamic typing and simpler tools (getattr, dir) instead of Java’s Reflection API.


Share Now :
Share

Python Reflection

Or Copy Link

CONTENTS
Scroll to Top