Book Image

Python Essentials

By : Steven F. Lott
Book Image

Python Essentials

By: Steven F. Lott

Overview of this book

Table of Contents (22 chapters)
Python Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 that happens when we make an instance of a class. Implicitly, the special method name of __new__() is used to create a bare object that is subsequently initialized by the __init__() method of the class. A metaclass allows us to change some of the...