Practical Metaprogramming in Python

Introduction

 

At first word Metaprogramming seems very funky and alien thing but if you have ever worked with decorators or metaclasses, your were doing metaprogramming there. In nutshell we can say metaprogramming is the code which manipulates code.

What we are going to learn?

  • General OOPS concepts in Python 
  • Descriptors
  • Metaclasses
  • Decorators
  • Generators 
  • Data Classes

General OOPS concepts in Python

Descriptors

Metaclasses

A metaclass is the class of a class. A class defines how an instance of the class (i.e. an object) behaves while a metaclass defines how a class behaves. A class is an instance of a metaclass.

Decorators

Decorators

A decorator is a function that creates a wrapper around another function

from functools import wraps

def debug(func):
  msg = func.__qualname__
  @wraps(func)
  def wrapper(*args, **kwargs):
    print(msg)
    return func(*args, **kwargs)
  return wrapper

@debug
def add(a, b):
  print(a+b)

add(1, 2)

https://repl.it/@bhansa/metaprogdecorators

Generators

Data Classes

Made with Slides.com