Registered: Feb, 2012
Re: Python Decorators II: Decorator Arguments
Posted: Feb 9, 2012 3:46 PM
I prefer an alternate form of your "decorator with arguments" class implementation that I would like to share with you. When I see this:
@decoratorWithArguments("Hello", "World", 42)
I think of this as a function that RETURNS a decorator as opposed to a decorator class that returns a function. That way, you don't need as much of a paradigm shift when using vs not using arguments, while still getting the benefit of not having to explicitly save arg1, arg2, and arg3. Here is how your example would be implemented using this concept:
NOTE: The strings that are printed do not exactly make sense with my implementation, but I left them like this to show the parallel to your implementation. The output of this program is identical to yours.
def decoratorWithArguments(arg1, arg2, arg3):
__print "Inside __init__():"
____def __init__(self, f):
______print "Inside __call__()"
______self.f = f
____def __call__(self, *args):
______print "Inside wrapped_f()"
______print "Decorator arguments:", arg1, arg2, arg3
______print "After f(*args)"
@decoratorWithArguments("Hello", "world", 42)
def sayHello(a1, a2, a3, a4):
__print 'sayHello arguments:', a1, a2, a3, a4
print "After decoration"
print "Preparing to call sayHello()"
sayHello("say", "hello", "argument", "list")
print "after first sayHello() call"
sayHello("a", "different", "set of", "arguments")
print "after second sayHello() call"