http://stackoverflow.com/questions/739654/understanding-pyth...
I would recommend the posted link for a first introduction -- it's short, explains decorators as clearly but more approachably, and talks about their application to classes, something the SO answer misses.
@jinja2_modifier
def awesomify(s):
return "%s is awesome" % s
(except it wasn't "jinja2_modifier", look it up in the docs)Mind you, I truly love Python decorators, but I just don't think the comparison to languages like LISP quite holds up. Maybe I'm just inexperienced, though...
https://github.com/daeken/Transformana/blob/master/test.py shows off various features if you're interested.
Edit: Here's the output from running the test, in case you want to see the AST format.
Hello world!
Yep, working.
Don't know.
['function',
None,
'test2',
(),
(),
0,
None,
['stmt', [['printnl', [['const', 'Hello from test2']], None]]]]
Hello from test2
['function', None, 'test3', (), (), 0, None, ['stmt', [['printnl', [['const', 'This should never be callable']], None]]]]https://github.com/built/Jane-Kelly/blob/master/guard.py
It'll let you redefine functions with different guard parameters. (@when("x=5"), @when("x>20"), etc.) Like you, I would also shudder to see this in production. But it was fun and shows off some of what's possible.
def mydec(func, decor_param_a, decor_param_b):
print 'decor_param_a = %s' % decor_param_a
def wrapper(*args, **kwargs):
print 'about to run function'
res = func(*args, **kwargs)
print 'done running function'
return res
return wrapper
Now just do: @mydecor('foo', 'bar')
def baz():
pass