pyxdeco: Python eXtraordinary Decorators

Decorators in Python are limited to action when the function they wrap is actually called. Which is fine and all, but they can be more useful. Or at least could be, if they allowed for hooks at definition or instance creation. I've packaged up a technique I've been using to do just that and released it as pyxdeco.

I wrote the code when trying to register instance methods as event listeners automatically when the instance was created. Decorator syntax made the most sense by far:

...
@on('click')
def click_listener(self):
    ...
...but Python decorators can't be used that way, since the decorator wouldn't be invoked until click_listener was actually called.

This package adds the ability to define decorators to be called at any of the three points of the function's existence: when the function is defined, when an instance of the class containing the function is created, and when the function is itself called (the last is of course not new, just a regular decorator, but is provided for consistency and completeness).

Code is on github, downloads available from pypi. Suggestions for examples or future development welcome.

2 comments

  • Larry Hastings  
    February 1, 2011 at 1:09 AM

    << Decorators in Python are limited to action when the function they wrap is actually called. >>

    Huh? Function decorators are called at the time the function is defined, not when it is called.

    The following code demonstrates this fact (using _ for indents):

    --
    def decorator(fn):
    _ print("decorator called")
    _ return fn

    print("defined")

    @decorator
    def foo():
    _ print("foo invoked")

    print("invoking foo")
    foo()
    --

    And since a decorator can return something else--a closure, say--you can contrive to have code called when the decorated function is called, too. In fact, since your library does its work through decorators, your statement on the limits of decorators is silly on its face.

  • Ian McCracken  
    February 1, 2011 at 9:55 AM

    Yes, you're right, sorry, that was imprecise of me. What I meant was that while the decorator itself is called at definition, the decorated function is limited in its effects.

Post a Comment