Charming Python: Decorators make magic easy

Python made metaprogramming possible, but each Python version has added slightly different -- and not quite compatible -- wrinkles to the way you accomplish metaprogramming tricks. Playing with first-class function objects has long been around, as have techniques for peaking and poking at magic attributes. With version 2.2, Python grew a custom metaclass mechanism that went a long way, but at the cost of melting users' brains. More recently, with version 2.4, Python has grown "decorators," which are the newest -- and by far the most user-friendly way, so far -- to perform most metaprogramming.

While metaprogramming is inherently a bit confusing, I think this article could have a been a little clearer. Still, it's a nice highlevel introduction to decorators.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Missing link to the article ?

Is it me or is the link missing in your post ?

Thanks. Fixed.

Thanks. Fixed.

decorators as poor man's macros

Decorators are nice and pythonic, but the more you play with them the more you realize that they are not much more than poor man's macros.
They nice thing is that they operate at runtime, so you can do some clever meta-polymorphic tricks with them.

The python PEP is actually a lot cleaner than the IBM article:
PEP 318

I'm not so sure about that

If you're referring to C-style macros, I'd say they're much more than that. You're not operating on text, you're taking a function and returning a new one when the function declaration is executed (i.e. when imported). It's no different than any other Python code.

You could do this before Python 2.4, but you'd have to decorate the function after its declaration via assignment, which is arguably less readable (as the PEP suggests).

As for "meta-polymorphic tricks", I'm not entirely sure what you mean.

I think he means Lisp/Scheme macros

(which are a very different beast indeed).


Don't decorators (over functions, classes and methods) give you the raw support needed for opt-in AOP?