Advanced techniques such as metaclasses, code injection, and call-stack walking harden Python for the enterprise. One novel use of Python's dynamic nature allows you to add private code access checking. Follow along to learn how.
by Gigi Sayfan
May 31, 2006
his article is the second in a two-part series that digs deep to explore the fascinating new-style Python object model, which was introduced in Python 2.2 and improved in 2.3 and 2.4. The object model and type system are very dynamic and allow quite a few interesting tricks. In part one I described the object model and type system, explored various entities, explained the life cycle of an object, and introduced some of the countless ways to modify and customize almost everything you thought immutable at runtime. In this article I will contrast meta-classes with decorators, explore the Python execution model and explain how to examine stack frames at runtime. Finally, I will demonstrate how to augment the Python language itself using these techniques. To do this I introduce a private access-checking feature that can be enforced at runtime.
Meta classes vs. Decorators
Philip Eby published a great article about Python 2.4 decorators in the May 2005 issue of Dr. Dobb's Journal, which I recommend if you want to understand them thoroughly. In brief, decorators are callable objects that accept the function they decorate as their sole argument. When a decorated function is invoked its decorator is executed. Most decorators will do something before and/or after invoking the original function. Decorators compete with meta-classes in the same evolutionary niche. Decorators have several advantages over meta-classes:
Decorators can be applied to every function (meta-classes can modify only class attributes)
Multiple decorators can be applied to a single function (each class can have only one meta-class)
It's quick, easy and you get access to all the articles on DevX.
This registration/login is to allow you to read articles on devx.com. Already a member?
To become a member of DevX.com create your Member Profile by completing the form below. Membership is free!