Introduction
The word "metaprogramming" refers to a program's ability to understand or manipulate itself. Metaclasses are a type of metaprogramming that Python allows for classes. Metaclasses are a nebulous OOP idea that underpins almost all Python code. Whether you realize it or not, you're utilizing them.
It's beneficial to learn about Python metaclasses because it gives a better grasp of Python classes in general. You never know when you'll find yourself in one of those circumstances where you need to use your metaclass.
Decorators and Meta-classes are used to achieve metaprogramming in Python.
Must Recommended Topic, Floor Division in Python, Swapcase in Python
“ Recommended Topic, Python Round Function”.
Decorators
A decorator allows you to add additional functionality to a function without changing its structure.
For example, we have the following three functions:
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
print(add(3, 2))
print(sub(3, 2))
print(mul(3, 2))
Output:
5
1
6
We now want to print the function name and the parameters when the function is called. We can do this by adding the print statements.
Adding print/log statements to all three methods is the default method. However, this sounds like a lot of effort, and we'd have to change the bodies of each function as well.
def add(x, y):
print("add is called with parameter {0},{1}".format(x,y))
return x + y
def sub(x, y):
print("sub is called with parameter {0},{1}".format(x,y))
return x - y
def mul(x, y):
print("mul is called with parameter {0},{1}".format(x,y))
return x * y
print(add(3, 2))
print(sub(3, 2))
print(mul(3, 2))
Output:
add is called with parameter 3,2
5
sub is called with parameter 3,2
1
mul is called with parameter 3,2
6
Is it possible for us to do better? This can be accomplished by writing a decorator function and leaving the existing function body alone.
def decorator(func):
def wrapper_function(*args):
print("{0} is called with parameter {1}".format(func.__name__, args))
return func(*args)
return wrapper_function
@decorator
def add(x, y):
return x + y
@decorator
def sub(x, y):
return x - y
@decorator
def mul(x, y):
return x * y
print(add(3, 2))
print(sub(3, 2))
print(mul(3, 2))
Output:
add is called with parameter (3, 2)
5
sub is called with parameter (3, 2)
1
mul is called with parameter (3, 2)
6
In the above code, we have used the decorator function to add print functionality to all three functions without changing the original function body. Decorators are, in essence, functions that take functions as input and return other functions. The decorator accepts a function in the above code and returns a wrapper function that adds the print functionality to the original functions. Thus, we have seen how to implement metaprogramming using decorators.
You can compile it with online python compiler.




