Python metaprogramming with decorators

This recipe for using decorators to load data structures caught my eye (thanks to the Daily Python URL) as an interesting metaprogramming technique.

Decorators are function transformers that can be applied declaratively to normal Python methods and functions using the much-disputed decorator syntax (see this previous LtU thread). This recipe uses decorators that return the supplied function unmodified, but as a side-effect register it in a dictionary of handlers for various value conversion operations. The decorator code itself is called when the module is loaded, so the dictionary is populated "on demand" at run-time. This makes an interesting contrast with compile-time metaprogramming techniques such as C++ template metaprogramming and the use of code generators and preprocessors.

I do not believe that C# attributes could easily be used in a similar way, as unlike Python decorators these receive no information about the entities they are attached to when they are instantiated.

Comment viewing options

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

C# attributes

I do not believe that C# attributes could easily be used in a similar way, as unlike Python decorators these receive no information about the entities they are attached to when they are instantiated.

In C#, using attributes on classes that derive from "ContextBoundObject", however, can lead to some powerful (dare I say AOP) code. I'm not familiar enough to Python decorators, however, to say if it is comparable.

Runtime / Loadtime / Compiletime

"The decorator code itself is called when the module is loaded, so the dictionary is populated "on demand" at run-time."

I don't think this really makes a difference, except that the data structure is "compressed" (in a generator function). In Lisp you would just use a compile-time macro to create that structure. In the case of normal object files in Unix loading is on-demand anyway.

So the basic distinction between having a data structure in the executable file image and decorators is if you want to just load the data structure as it is from disk, or create it at runtime (which might be slow, depending on what it does).

Well, this just doesn't seem too revolutionary to me :)