Python Advanced: What is Reflection in Python Programming

Home /

Table of Contents

Python Reflection

Reflective programming, often known as reflection, is the ability of a process to investigate, introspect, and adjust its structure and behavior. The practical implementation of behaviorally reflective languages is a significant problem. By definition, behavioral reflection allows a program to alter its code, as well as the semantics and implementation of its programming language, even while it is running. This late-binding of language semantics favors interpretative approaches, yet compilers are definitely required to make reflective languages efficient and, hence, attractive. 


def reflection(value):
   type_val = type(value)
   value_0 = type_val()
   if value == value_0:
       return value_0
   prev = reflection(value[1:])
   value_1 = value[0:1]
   reflected = prev + value_1
   return reflected
val1 = [10, 20, 30, 40]
test1 = reflection(val1)
print("Original Value: ",val1)
print("Reflected Value: ",test1)
val2 = "Python and Javascript"
test2 = Reflection(val2)
print("Original Value: ",val2)
print("Reflected Value: ",test2)


Original Value:  [10, 20, 30, 40]
Reflected Value:  [40, 30, 20, 10]
Original Value:  Python and Javascript
Reflected Value:  tpircsavaJ dna nohtyP

Functions that Enable Reflection

There are some functions. which can be used for reflective programming in Python. We will now learn about those methods and examples. Such as, Type(), isinstance(), callable(), dir(), and getattr() .

Type: Python provides a built-in function called type that is useful for determining the type of the variable used in the program during runtime. The standard approach to check for type in Python is shown below.


number = 38
string = "Python"
list = [34, 35, 36]


<class 'int'>
<class 'str'>
<class 'list'>

isinstance():  The isinstance() method determines if the object (first parameter) is an instance or subclass of the information class (second argument). Return any element of the tuple as false if the item is not an instance or subclass of a class. A TypeError exception is thrown if class info is not a type or tuple of types.


cg = 3.97
cgpa = isinstance(cg, float)
print("is a float:", cgpa)
num = 345
number = isinstance(num, int)
print("is an integer:", number)
string = isinstance("Python", str)
print("is a string:", string)
tpl = ('X', 'Y', 'Z', (1,2,3,4))
tuple1 = isinstance(tpl,tuple)
print("is a tuple:", tuple1)
st = {1,1,2,3,4,4,4,5}
set1 = isinstance(st,set)
print("is a set:", set1)
lst = [23, 67, 98, 2345]
list1 = isinstance(lst,list)
print("is a list:", list1)
dct = {1:"Python", 2:"Javascript", 3:"Rust"}
dict1 = isinstance(dct,dict)
print("is a dict:", dict1)


is a float: True
is an integer: True
is a string: True
is a tuple: True
is a set: True
is a list: True
is a dict: True

callable(): A callable is something that can be called. Determines if an item may be called. By including a __call__() function, a class may be made callable. If the object supplied appears to be callable, the callable() function returns True. If it does not, it returns False.


variable = 438
def func():
 print("This is a function")
function = func
if (callable(variable)):
   print("variable is callable")
   print("variable is not callable")
if (callable(function)):
   print("function is callable")
   print("function is not callable")


variable is not callable
function is callable

dir(): The dir() function attempts to return a list of the object’s valid attributes. The dir() function attempts to return a list of the object’s valid attributes.

If the object has a __dir__() method, it will be called and the list of attributes must be returned.

If the object lacks a __dir()__ method, this function attempts to obtain information from the __dict__ attribute (if specified) and the type object. The list produced by dir() may not be comprehensive in this scenario.

Getattr: The getattr() function returns the value of an object’s named attribute. If no match is discovered, it returns the function’s default value. The object, name, and default arguments are sent to the getattr method (optional).

One of the main reasons for using reflection in Python is to make code more flexible and dynamic. Reflection enables the creation of programs that can adapt to different situations, inputs, and outputs. It allows the creation of code that can be reused in a variety of ways, making it more maintainable and scalable.

Reflection is also important in Python because it enables the creation of metaclasses, which are classes that define the behavior and structure of other classes. Metaclasses allow developers to customize the creation of classes and objects, making it possible to create highly specialized objects with unique properties and behaviors.

Reflection is also essential for debugging and testing purposes. It allows developers to inspect objects and their attributes, methods, and properties, and to modify them on the fly. This can be useful for tracking down bugs and testing code, as it enables developers to see how their code is working in real-time.

Share The Blog With Your Friends
Other Recommended Article