Part 4 · Section 14
Metaprogramming
Metaprogramming means writing code whose job is to create or modify other code: functions, classes, even the rules for how attributes are looked up. You’ve been doing a light form of it for a while. Every decorator rewraps a function, and every descriptor changes what the dot operator does. This section goes all the way down. You’ll see that a class statement is just a call to type, that you can replace type with your own metaclass, and that Python gives you a hook at nearly every stage of building a class and reading or writing its attributes.
This is powerful, and it’s easy to overdo. So alongside each technique, you’ll learn which lighter tool (a class decorator, __init_subclass__, a descriptor, @dataclass) does the same job more simply.
In this section you’ll learn:
- how
__new__creates an instance before__init__initializes it, and when to override it - how a
classstatement works: running the body in a namespace and callingtype(name, bases, namespace) - how to subclass
typeand plug the result in as a metaclass, with extra keyword parameters - how class decorators and decorator classes work, and how they compare with metaclasses
__init_subclass__and__set_name__, the modern hooks that make many metaclasses unnecessary__prepare__, and the complete class creation pipeline from start to finish- three applications: generated “struct” classes, singletons, and config classes built from
.inifiles - the exact rules for
__getattribute__,__getattr__,__setattr__and__delattr__, and how to use them without infinite recursion
Lectures
- 01Decorators and Descriptors - Review✓
- 02The __new__ Method✓
- 03How Classes are Created✓
- 04Inheriting from type✓
- 05Metaclasses✓
- 06Class Decorators✓
- 07Decorator Classes✓
- 08Metaclasses vs Class Decorators✓
- 09Metaclass Parameters✓
- 10The __prepare__ Method✓
- 11Metaprogramming Application 1✓
- 12Metaprogramming - Application 2✓
- 13Metaprogramming - Application 3✓
- 14Attribute Read Accessors✓
- 15Attribute Write Accessors✓
- 16Accessors - Application✓