Skip to content

Reflection in Python

Reflection in Python : Reflect on Your Code

Reflection is the ability of a program to examine and modify its structure and behavior at runtime. Reflection is a powerful feature of many programming languages, including Python. Reflection allows you to inspect and modify objects, classes, functions, and modules at runtime. Reflection is implemented in Python using the inspectinspect module.

What is Reflection?

Reflection is the ability of a program to examine and modify its structure and behavior at runtime. Reflection allows you to inspect and modify objects, classes, functions, and modules at runtime. Reflection is a powerful feature of many programming languages, including Python. Reflection is used in many advanced programming techniques, such as metaprogramming, introspection, and dynamic code generation.

Reflection in Python

Reflection in Python is implemented using the inspectinspect module. The inspectinspect module provides functions for inspecting live objects, such as modules, classes, and functions. The inspectinspect module allows you to get information about objects, such as their attributes, methods, and source code. The inspectinspect module also provides functions for examining the call stack, getting the source code of functions, and formatting code objects.

Using the inspectinspect Module

The inspectinspect module provides several functions for inspecting objects in Python. Some of the most commonly used functions in the inspectinspect module are:

  • inspect.ismodule()inspect.ismodule(): Returns TrueTrue if the object is a module.
  • inspect.isclass()inspect.isclass(): Returns TrueTrue if the object is a class.
  • inspect.isfunction()inspect.isfunction(): Returns TrueTrue if the object is a function.
  • inspect.ismethod()inspect.ismethod(): Returns TrueTrue if the object is a method.
  • inspect.isbuiltin()inspect.isbuiltin(): Returns TrueTrue if the object is a built-in function or method.
  • inspect.isroutine()inspect.isroutine(): Returns TrueTrue if the object is a function or method.
  • inspect.getmembers()inspect.getmembers(): Returns a list of all members of an object.
  • inspect.getsource()inspect.getsource(): Returns the source code of an object.
  • inspect.getfile()inspect.getfile(): Returns the file name in which an object was defined.
  • inspect.getmodule()inspect.getmodule(): Returns the module in which an object was defined.
  • inspect.getdoc()inspect.getdoc(): Returns the docstring of an object.
  • inspect.isabstract()inspect.isabstract(): Returns TrueTrue if the object is an abstract base class.

Some more functions:

  • isinstance()isinstance(): Returns TrueTrue if the object is an instance of a class.
  • issubclass()issubclass(): Returns TrueTrue if the object is a subclass of a class.
  • getattr()getattr(): Returns the value of an attribute of an object.
  • setattr()setattr(): Sets the value of an attribute of an object.
  • delattr()delattr(): Deletes an attribute of an object.
  • hasattr()hasattr(): Returns TrueTrue if an object has a given attribute.
  • callable()callable(): Returns TrueTrue if an object is callable.
  • dir()dir(): Returns a list of all attributes of an object.
  • vars()vars(): Returns the __dict____dict__ attribute of an object.
  • type()type(): Returns the type of an object.
  • id()id(): Returns the unique identifier of an object.

Example

Here is an example of using the inspectinspect module to inspect a module in Python:

Inspecting a Module
import inspect
 
def hello():
    return "Hello, World!"
 
print(inspect.ismodule(inspect))
print(inspect.ismodule(hello))
print(insprint.isfunction(hello))
Inspecting a Module
import inspect
 
def hello():
    return "Hello, World!"
 
print(inspect.ismodule(inspect))
print(inspect.ismodule(hello))
print(insprint.isfunction(hello))

In the above code:

  • We import the inspectinspect module.
  • We define a function hello()hello() that returns the string "Hello, World!""Hello, World!".
  • We use the inspect.ismodule()inspect.ismodule() function to check if the inspectinspect module is a module.
  • We use the inspect.ismodule()inspect.ismodule() function to check if the hellohello function is a module.
  • We use the inspect.isfunction()inspect.isfunction() function to check if the hellohello function is a function.

The output of the above code will be:

Output
C:/Users/username/desktop>python inspect.py
True
False
True
Output
C:/Users/username/desktop>python inspect.py
True
False
True

isinstance()isinstance() and issubclass()issubclass() Functions

The isinstance()isinstance() function is used to check if an object is an instance of a class. The issubclass()issubclass() function is used to check if a class is a subclass of another class. Here is an example of using the isinstance()isinstance() and issubclass()issubclass() functions in Python:

Using isinstance() and issubclass()
class A:
    pass
 
class B(A):
    pass
 
objA = A()
objB = B()
print(isinstance(objA, A))
print(isinstance(objB, A))
print(issubclass(B, A))
Using isinstance() and issubclass()
class A:
    pass
 
class B(A):
    pass
 
objA = A()
objB = B()
print(isinstance(objA, A))
print(isinstance(objB, A))
print(issubclass(B, A))

Here, we define two classes AA and BB. The class BB is a subclass of the class AA. We create instances of the classes AA and BB and use the isinstance()isinstance() and issubclass()issubclass() functions to check if the instances are instances of the classes and if the classes are subclasses of each other.

The output of the above code will be:

Output
C:/Users/username/desktop>python isinstance.py
True
True
True
Output
C:/Users/username/desktop>python isinstance.py
True
True
True

getattr()getattr(), setattr()setattr(), delattr()delattr(), and hasattr()hasattr() Functions

The getattr()getattr(), setattr()setattr(), delattr()delattr(), and hasattr()hasattr() functions are used to get, set, delete, and check the existence of attributes of an object, respectively. Here is an example of using the getattr()getattr(), setattr()setattr(), delattr()delattr(), and hasattr()hasattr() functions in Python:

Using getattr(), setattr(), delattr(), and hasattr()
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
person = Person("Alice", 30)
print(getattr(person, "name"))
setattr(person, "age", 35)
print(getattr(person, "age"))
delattr(person, "age")
print(hasattr(person, "age"))
Using getattr(), setattr(), delattr(), and hasattr()
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
person = Person("Alice", 30)
print(getattr(person, "name"))
setattr(person, "age", 35)
print(getattr(person, "age"))
delattr(person, "age")
print(hasattr(person, "age"))

Here, we define a class PersonPerson with two attributes namename and ageage. We create an instance of the PersonPerson class and use the getattr()getattr(), setattr()setattr(), delattr()delattr(), and hasattr()hasattr() functions to get, set, delete, and check the existence of the attributes of the object.

The output of the above code will be:

Output
C:/Users/username/desktop>python getattr.py
Alice
35
False
Output
C:/Users/username/desktop>python getattr.py
Alice
35
False

callable()callable() Function

The callable()callable() function is used to check if an object is callable. An object is callable if it can be called like a function. Here is an example of using the callable()callable() function in Python:

Using callable()
def hello():
    return "Hello, World!"
 
print(callable(hello))
print(callable("Hello, World!"))
Using callable()
def hello():
    return "Hello, World!"
 
print(callable(hello))
print(callable("Hello, World!"))

Here, we define a function hello()hello() that returns the string "Hello, World!""Hello, World!". We use the callable()callable() function to check if the function hello()hello() is callable and if the string "Hello, World!""Hello, World!" is callable.

The output of the above code will be:

Output
C:/Users/username/desktop>python callable.py
True
False
Output
C:/Users/username/desktop>python callable.py
True
False

dir()dir() and vars()vars() Functions

The dir()dir() function is used to get a list of all attributes of an object. The vars()vars() function is used to get the __dict____dict__ attribute of an object. Here is an example of using the dir()dir() and vars()vars() functions in Python:

Using dir() and vars()
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
person = Person("Alice", 30)
print(dir(person))
print(vars(person))
Using dir() and vars()
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
person = Person("Alice", 30)
print(dir(person))
print(vars(person))

Here, we define a class PersonPerson with two attributes namename and ageage. We create an instance of the PersonPerson class and use the dir()dir() and vars()vars() functions to get a list of all attributes of the object and the __dict____dict__ attribute of the object.

The output of the above code will be:

Output
C:/Users/username/desktop>python dir.py
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name']
{'name': 'Alice', 'age': 30}
Output
C:/Users/username/desktop>python dir.py
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name']
{'name': 'Alice', 'age': 30}

type()type() and id()id() Functions

The type()type() function is used to get the type of an object. The id()id() function is used to get the unique identifier of an object. Here is an example of using the type()type() and id()id() functions in Python:

Using type() and id()
class Person:
    pass
 
person = Person()
print(type(person))
print(id(person))
Using type() and id()
class Person:
    pass
 
person = Person()
print(type(person))
print(id(person))

Here, we define a class PersonPerson and create an instance of the PersonPerson class. We use the type()type() function to get the type of the object and the id()id() function to get the unique identifier of the object.

The output of the above code will be:

Output
C:/Users/username/desktop>python type.py
<class '__main__.Person'>
140735674221376
Output
C:/Users/username/desktop>python type.py
<class '__main__.Person'>
140735674221376

Conclusion

Reflection is a powerful feature of Python that allows you to examine and modify objects, classes, functions, and modules at runtime. Reflection is implemented in Python using the inspectinspect module. The inspectinspect module provides functions for inspecting live objects, such as modules, classes, and functions. By using the inspectinspect module, you can get information about objects, such as their attributes, methods, and source code. Reflection is used in many advanced programming techniques, such as metaprogramming, introspection, and dynamic code generation. For more information on the inspectinspect module, you can refer to the official Python documentation. For more tutorials on Python Central Hub.

Was this page helpful?

Let us know how we did