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:

Lectures

  1. 01Decorators and Descriptors - Review✓
  2. 02The __new__ Method✓
  3. 03How Classes are Created✓
  4. 04Inheriting from type✓
  5. 05Metaclasses✓
  6. 06Class Decorators✓
  7. 07Decorator Classes✓
  8. 08Metaclasses vs Class Decorators✓
  9. 09Metaclass Parameters✓
  10. 10The __prepare__ Method✓
  11. 11Metaprogramming Application 1✓
  12. 12Metaprogramming - Application 2✓
  13. 13Metaprogramming - Application 3✓
  14. 14Attribute Read Accessors✓
  15. 15Attribute Write Accessors✓
  16. 16Accessors - Application✓

Practice: quiz & exercises

12 quiz questions · 4 coding exercises

Go to practice →