Chapter 13. Metaprogramming and Decorators

The bulk of what we've covered has been programming—writing Python statements to process data. We can also use Python to process Python instead of processing data. We'll call this metaprogramming. We'll look at two aspects: decorators and metaclasses.

A decorator is a function that accepts a function as an argument and returns a function. We can use this to add features to a function without repeating the feature in several different function definitions. A decorator prevents copy-and-paste programming. We often use this for logging, audit, or security purposes; these are things that will cut across a number of class or function definitions.

A metaclass definition will extend the essential object creation ...

Get Python Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.