Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Introduction to MetaClasses

Introduction to MetaClasses

In this talk, we’ll explore metaclasses in Python and learn how to leverage them for having custom behavior across the codebase. We’ll explore the infamous type and how it comes into play in metaclasses. Lastly, we’ll cover how metaclasses can be useful for Abstract Base Classes which comes from the abc module in the standard library.

A class is a blueprint for an object. It describes how an instance of the class (ie an object) would behave. A metaclass is the class of a class. It defines how a class behaves. When you define a class in Python, its metaclass is called which when combined with __init__ and __new__ methods allows doing extra things like registering class with some registry or replace it entirely with something different.

The whole magic comes with type. It is a metaclass in Python, which itself is a class and it is of its own type. (yes, inception!).

Sanyam Khurana

September 09, 2020
Tweet

More Decks by Sanyam Khurana

Other Decks in Programming

Transcript

  1. def __who_am_i__(): • One of you! A part of the

    community • Goes by “CuriousLearner” over the web / IRC • FOSS contributor • Bug triager for CPython • Contributor to Django and Mozilla’s ecosystem of projects • Maintainer for django-phone-verify
  2. Classes are objects ErSanyamKhurana CuriousLearner Assign class to a variable

    Copy class Add attributes to a class Pass class as parameters to a function Classes are objects
  3. The esoteric `type` ErSanyamKhurana CuriousLearner Creating classes using type Name

    of the class to be created Tuple of all the base classes that the new class should inherit from
  4. The esoteric `type` ErSanyamKhurana CuriousLearner Creating classes using type Name

    of the class to be created Tuple of all the base classes that the new class should inherit from Dictionary of all the attributes of new class in key value pairs
  5. The esoteric `type` ErSanyamKhurana CuriousLearner Creating classes using type That’s

    the entire magic of dynamic class creation that happens when the interpreter sees the block of code indicating a class. type is the default metaclass
  6. The world of Analogies ErSanyamKhurana CuriousLearner child : parent ::

    parent : grandparent object : class :: class : metaclass
  7. What’s a MetaClass : Revisited ErSanyamKhurana CuriousLearner It’s a class

    factory. Provides a way to create classes on the fly. Let’s you hook-into the class creation logic to validate things ensuring the newly derived class conforms to a certain API standard.
  8. Deeper look at MetaClasses • Called before class body is

    executed • Must return an instance of dict with local namespace for all the code in the class body. • PEP-3115 — Metaclasses in Python 3000 ErSanyamKhurana CuriousLearner __prepare__ method
  9. Deeper look at MetaClasses • The __new__ method is the

    constructor — generates the new instance • __init__ is just a initializer — called after instance is created • __new__ is looked up statically on the instance (class) itself and not up in the hierarchy such as in the metaclass. ErSanyamKhurana CuriousLearner __new__ & __init__ method
  10. Multiple Inheritance in Metaclasses Only works when you have single

    root MetaClass from which all base classes inherit from. ErSanyamKhurana CuriousLearner
  11. Multiple Inheritance in Metaclasses Only works when you have single

    root MetaClass from which all base classes inherit from. ErSanyamKhurana CuriousLearner
  12. When to use MetaClasses? Before you uses metaclass, ask yourself:

    - Can I accomplish what I want with a decorator? If yes, then choose decorator. - Am I trying to provide an API for programmers to use (using my library/framework), specifically for derived classes? Would MetaClass reduce the amount of code an application programmer has to write? If yes, then use metaclasses. ErSanyamKhurana CuriousLearner
  13. Use cases of MetaClasses • Validation framework for attributes of

    classes • Hook into the class creation process to control either the inheritance to or fro from the custom class. • Emulating behaviour in other programming languages, such as making a final class as seen in Java. • Hook into the class creation process to maintain order of class definitions (not instance creations) • Controlling meta stuff about the class like enforcing all the private methods of the class to have docstrings. ErSanyamKhurana CuriousLearner
  14. References • https://stackoverflow.com/questions/100003/what-are-metaclasses-in- python • https://stackoverflow.com/questions/392160/what-are-some-concrete- use-cases-for-metaclasses • https://eli.thegreenplace.net/2011/08/14/python-metaclasses-by- example/

    • https://blog.ionelmc.ro/2015/02/09/understanding-python-metaclasses/ • https://www.python.org/dev/peps/pep-3115/ • https://docs.python.org/3/reference/datamodel.html#customizing-class- creation ErSanyamKhurana CuriousLearner