Comment on Introduction to Python DecoratorsparentComments−peregrine14yThat would be nice! I poked around djangos source to see how they created decorators that take parameters but never thought how that worked was very intuitive.−IgorPartola14yIt's easy: 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−stock_toaster14yIt is a bit more work if you want to create a decorator that can:* decorate a class* decorate a method* have arguments* have no argumentsextremely contrived example:http://pastebin.com/GBuYL2afNote that the above only works for 'new style' classes (otherwise the type signature is not 'type').edit: dumped code in a pastebin. it got kind of long.
Comments
That would be nice! I poked around djangos source to see how they created decorators that take parameters but never thought how that worked was very intuitive.
It's easy:
Now just do:It is a bit more work if you want to create a decorator that can:
* decorate a class
* decorate a method
* have arguments
* have no arguments
extremely contrived example:
http://pastebin.com/GBuYL2af
Note that the above only works for 'new style' classes (otherwise the type signature is not 'type').
edit: dumped code in a pastebin. it got kind of long.