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 inspect
inspect
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 inspect
inspect
module. The inspect
inspect
module provides functions for inspecting live objects, such as modules, classes, and functions. The inspect
inspect
module allows you to get information about objects, such as their attributes, methods, and source code. The inspect
inspect
module also provides functions for examining the call stack, getting the source code of functions, and formatting code objects.
Using the inspect
inspect
Module
The inspect
inspect
module provides several functions for inspecting objects in Python. Some of the most commonly used functions in the inspect
inspect
module are:
inspect.ismodule()
inspect.ismodule()
: ReturnsTrue
True
if the object is a module.inspect.isclass()
inspect.isclass()
: ReturnsTrue
True
if the object is a class.inspect.isfunction()
inspect.isfunction()
: ReturnsTrue
True
if the object is a function.inspect.ismethod()
inspect.ismethod()
: ReturnsTrue
True
if the object is a method.inspect.isbuiltin()
inspect.isbuiltin()
: ReturnsTrue
True
if the object is a built-in function or method.inspect.isroutine()
inspect.isroutine()
: ReturnsTrue
True
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()
: ReturnsTrue
True
if the object is an abstract base class.
Some more functions:
isinstance()
isinstance()
: ReturnsTrue
True
if the object is an instance of a class.issubclass()
issubclass()
: ReturnsTrue
True
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()
: ReturnsTrue
True
if an object has a given attribute.callable()
callable()
: ReturnsTrue
True
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 inspect
inspect
module to inspect a module in Python:
import inspect
def hello():
return "Hello, World!"
print(inspect.ismodule(inspect))
print(inspect.ismodule(hello))
print(insprint.isfunction(hello))
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
inspect
inspect
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 theinspect
inspect
module is a module. - We use the
inspect.ismodule()
inspect.ismodule()
function to check if thehello
hello
function is a module. - We use the
inspect.isfunction()
inspect.isfunction()
function to check if thehello
hello
function is a function.
The output of the above code will be:
C:/Users/username/desktop>python inspect.py
True
False
True
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:
class A:
pass
class B(A):
pass
objA = A()
objB = B()
print(isinstance(objA, A))
print(isinstance(objB, A))
print(issubclass(B, A))
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 A
A
and B
B
. The class B
B
is a subclass of the class A
A
. We create instances of the classes A
A
and B
B
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:
C:/Users/username/desktop>python isinstance.py
True
True
True
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:
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"))
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 Person
Person
with two attributes name
name
and age
age
. We create an instance of the Person
Person
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:
C:/Users/username/desktop>python getattr.py
Alice
35
False
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:
def hello():
return "Hello, World!"
print(callable(hello))
print(callable("Hello, World!"))
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:
C:/Users/username/desktop>python callable.py
True
False
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:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Alice", 30)
print(dir(person))
print(vars(person))
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 Person
Person
with two attributes name
name
and age
age
. We create an instance of the Person
Person
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:
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}
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:
class Person:
pass
person = Person()
print(type(person))
print(id(person))
class Person:
pass
person = Person()
print(type(person))
print(id(person))
Here, we define a class Person
Person
and create an instance of the Person
Person
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:
C:/Users/username/desktop>python type.py
<class '__main__.Person'>
140735674221376
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 inspect
inspect
module. The inspect
inspect
module provides functions for inspecting live objects, such as modules, classes, and functions. By using the inspect
inspect
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 inspect
inspect
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