Simplifying the Code: Meta-Programming in Python | Nitor Infotech
Send me Nitor Infotech's Monthly Blog Newsletter!
×
nitor logo
  • Company
    • About
    • Leadership
    • Partnership
  • Resource Hub
  • Blog
  • Contact
nitor logo
Add more content here...
Artificial intelligence Big Data Blockchain and IoT
Business Intelligence Careers Cloud and DevOps
Digital Transformation Healthcare IT Manufacturing
Mobility Product Modernization Software Engineering
Thought Leadership
Aastha Sinha Abhijeet Shah Abhishek Suranglikar
Abhishek Tanwade Abhishek Tiwari Ajinkya Pathak
Amit Pawade Amol Jadhav Ankita Kulkarni
Antara Datta Anup Manekar Ashish Baldota
Chandra Gosetty Chandrakiran Parkar Deep Shikha Bhat
Dr. Girish Shinde Gaurav Mishra Gaurav Rathod
Gautam Patil Harish Singh Chauhan Harshali Chandgadkar
Kapil Joshi Madhavi Pawar Marappa Reddy
Milan Pansuriya Minal Doiphode Mohit Agarwal
Mohit Borse Nalini Vijayraghavan Neha Garg
Nikhil Kulkarni Omkar Ingawale Omkar Kulkarni
Pooja Dhule Pranit Gangurde Prashant Kamble
Prashant Kankokar Priya Patole Rahul Ganorkar
Ramireddy Manohar Ravi Agrawal Robin Pandita
Rohan Chavan Rohini Wwagh Sachin Saini
Sadhana Sharma Sambid Pradhan Sandeep Mali
Sanjeev Fadnavis Saurabh Pimpalkar Sayanti Shrivastava
Shardul Gurjar Shravani Dhavale Shreyash Bhoyar
Shubham Kamble Shubham Muneshwar Shubham Navale
Shweta Chinchore Sidhant Naveria Souvik Adhikary
Sreenivasulu Reddy Sujay Hamane Tejbahadur Singh
Tushar Sangore Vasishtha Ingale Veena Metri
Vidisha Chirmulay Yogesh Kulkarni
Software Engineering | 09 Apr 2020 |   9 min

Simplifying the Code: Meta-Programming in Python

featured image

A short tutorial about streamlining your code with Decorators and Meta-classes

Meta-programming in Python is a tough, albeit interesting, nut to crack.  This article is a guide for those who want to learn about two crucial features of meta-programming – decorators and meta classes.

What Is Meta-Programming?

In short, meta-programming is the act of writing code that manipulates code. However, without understanding the concept, the above one-liner probably won’t excite the grey cells. Let’s delve deeper to understand meta-programming in the context of Python.

Meta-programming in Python can be stated as: “Meta-programming is an act of building functions and classes that can manipulate code by modifying, wrapping existing code, or generating code.” However, this may seem really difficult to understand at one go. Therefore, it’s necessary to get familiar with the relevant terms.

There are two vital elements to achieve meta-programming in Python:

  • Decorators
  • Meta-classes

Decorators:

A decorator is a way of adding new functionality to an existing function without modifying its original structure.

Consider the following three functions:

def add(x, y):

Broadly speaking, a decorator helps to avoid repetition when printing the function name and parameter values each time the function is called.

With reference to the code block above, consider a situation in which we need to print the function name and parameter values when the function is called. This should be applicable to all three functions above.

The native way is to add print/log statements to all three functions. However, this is repetitive work and we would also need to modify each function body.

Here’s what that would look like:

def add(x, y):

It is clear that the same output can be achieved in a more efficient manner. To do this, we need to write a decorator function. The proper use of a decorator can cut down the series of mundane tasks of modifying each function body.

def my_decorator(func):

In the above code snippet, my_decorator is a decorator function. We decorate all three functions with @my_decorator and we have not touched the existing function body to add this print functionality.

Therefore, a decorator function is, at its core, a higher-order function that take a function as an argument and returns another function.

In the above code, my_decorator takes a function as an argument and returns wrapper_function as a result. wrapper_function adds print functionality to func.

Now, let’s switch to another crucial element of meta-programming.

Meta-Classes:

A special class in itself, a meta-class would be best described as the class of a class. Instead of defining the behaviour of its own instances like an ordinary class, a meta-class defines the behaviour of an ordinary class and its instance. A class, in this case, would thus be an instance of a meta-class.

Using a meta-class, methods or fields can be added or subtracted from an ordinary class. Python has one special class, the type class, which is by default a meta-class. All custom type classes must inherit from the type class .In this example, the class calchas three class methods. A meta-class can be used to provide a functionality such as debug, to all the methods at once.

class Calc():

To do this, First, we need to create a meta-class MetaClassDebug, with debug functionality, and make the Calc class inherit from MetaClassDebug. When we call any method from the Calc class, it will be invoked with our debug_function.

def debug_function(func):

def wrapper(*args, **kwargs):
print(“{0} is called with parameter {1}”.format(func.__qualname__, args[1:]))
return func(*args, **kwargs)

return wrapper

def debug_all_methods(cls):

for key, val in vars(cls).items():
if callable(val):
setattr(cls, key, debug_function(val))
return cls

class MetaClassDebug(type):

def __new__(cls, clsname, bases, clsdict):
obj = super().__new__(cls, clsname, bases, clsdict)
obj = debug_all_methods(obj)
return obj

class Calc(metaclass=MetaClassDebug):
def add(self, x, y):
return x + y

def sub(self, x, y):
return x – y

def mul(self, x, y):
return x * y

calc = Calc()
print(calc.add(2, 3))
print(calc.sub(2, 3))
print(calc.mul(2, 3))

**************** output ****************

Calc.add is called with parameter (2, 3)
5
Calc.sub is called with parameter (2, 3)
-1
Calc.mul is called with parameter (2, 3)
6

In the above code, the

With meta-classes, not only can new behaviour be added to all methods within a class, but the instance creation of a class can also be controlled. With meta-classes, methods and fields can also be added or removed from classes.

Conclusion:

This article described decorators and meta-classes, two types of meta-programming in Python. If you need some guidance with fine-tuning your organization’s programming capabilities, please reach out to us at marketing@nitorinfotech.com. Nitor Infotech’s dedicated technology experts and programmers can help throughout your journey, from initial assessment to monitoring.

The article portrayed the relationship among instances, classes, and, meta-classes in Python.  Are you contemplating implementation of custom meta-classes by sub classing the default type meta-class of Python? If you are then, rely on Nitor Infotech’s dedicated technology experts and programmers, who can help throughout your entire programming and modernization journey, from initial assessment to implementation and monitoring.

Related Topics

Artificial intelligence

Big Data

Blockchain and IoT

Business Intelligence

Careers

Cloud and DevOps

Digital Transformation

Healthcare IT

Manufacturing

Mobility

Product Modernization

Software Engineering

Thought Leadership

<< Previous Blog fav Next Blog >>
author image

Nitor Infotech Blog

Nitor Infotech is a leading software product development firm serving ISVs and enterprise customers globally.

   

You may also like

featured image

10 Heuristic Principles in UX Engineering

Say, you’ve built a modern, cutting-edge application. It has a complex, multi-layered user interface (UI), that is the basis for some amazing features. Since you’re the one who has built the applic...
Read Blog


featured image

ETL Testing: A Detailed Guide

Just in case the term is new to you, ETL is defined from data warehousing and stands for Extract-Transform-Load. It covers the process of how the data is loaded from the multiple source system to t...
Read Blog


featured image

Getting Started with ArcGIS Online

GeoServer is an open-source server that facilitates the sharing, processing and editing of geospatial data. When we are dealing with a large set of geospatial d...
Read Blog


subscribe

Subscribe to our fortnightly newsletter!

We'll keep you in the loop with everything that's trending in the tech world.

Services

    Modern Software Engineering


  • Idea to MVP
  • Quality Engineering
  • Product Engineering
  • Product Modernization
  • Reliability Engineering
  • Product Maintenance

    Enterprise Solution Engineering


  • Idea to MVP
  • Strategy & Consulting
  • Enterprise Architecture & Digital Platforms
  • Solution Engineering
  • Enterprise Cognition Engineering

    Digital Experience Engineering


  • UX Engineering
  • Content Engineering
  • Peer Product Management
  • RaaS
  • Mobility Engineering

    Technology Engineering


  • Cloud Engineering
  • Cognitive Engineering
  • Blockchain Engineering
  • Data Engineering
  • IoT Engineering

    Industries


  • Healthcare
  • Retail
  • Manufacturing
  • BFSI
  • Supply Chain

    Company


  • About
  • Leadership
  • Partnership
  • Contact Us

    Resource Hub


  • White papers
  • Brochures
  • Case studies
  • Datasheet

    Explore More


  • Blog
  • Career
  • Events
  • Press Releases
  • QnA

About


With more than 16 years of experience in handling multiple technology projects across industries, Nitor Infotech has gained strong expertise in areas of technology consulting, solutioning, and product engineering. With a team of 700+ technology experts, we help leading ISVs and Enterprises with modern-day products and top-notch services through our tech-driven approach. Digitization being our key strategy, we digitally assess their operational capabilities in order to achieve our customer's end- goals.

Get in Touch


  • +1 (224) 265-7110
  • marketing@nitorinfotech.com

We are Social 24/7


© 2023 Nitor Infotech All rights reserved

  • Terms of Usage
  • Privacy Policy
  • Cookie Policy
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it. Accept Cookie policy