Decorators¶
-
@
decorator
¶ Transforms a flat wrapper into a decorator with or without arguments.
@decorator
passes specialcall
object as a first argument to a wrapper. A resulting decorator will preserve function module, name and docstring. It also adds__wrapped__
attribute referring to wrapped function and__original__
attribute referring to innermost wrapped one.Here is a simple logging decorator:
@decorator def log(call): print call._func.__name__, call._args, call._kwargs return call()
call
object also supports by name arg introspection and passing additional arguments to decorated function:@decorator def with_phone(call): # call.request gets actual request value upon function call request = call.request # ... phone = Phone.objects.get(number=request.GET['phone']) # phone arg is added to *args passed to decorated function return call(phone) @with_phone def some_view(request, phone): # ... some code using phone return # ...
A better practice would be adding keyword argument not positional. This makes such decorators more composable:
@decorator def with_phone(call): # ... return call(phone=phone) @decorator def with_user(call): # ... return call(user=user) @with_phone @with_user def some_view(request, phone=None, user=None): # ... return # ...
If a function wrapped with
@decorator
has arguments other thancall
, then decorator with arguments is created:@decorator def joining(call, sep): return sep.join(call())
You can see more examples in
flow
anddebug
submodules source code.
-
@
contextmanager
(func)¶ A decorator helping to create context managers. Resulting functions also behave as decorators.
A simple example:
@contextmanager def tag(name): print "<%s>" % name, yield print "</%s>" % name with tag("h1"): print "foo", # -> <h1> foo </h1>
Using as decorator:
@tag('strong') def shout(text): print text.upper() shout('hooray') # -> <strong> HOORAY </strong>
-
@
wraps
(wrapped[, assigned][, updated])¶ An utility to pass function metadata from wrapped function to a wrapper. Copies all function attributes including
__name__
,__module__
and__doc__
.In addition adds
__wrapped__
attribute referring to the wrapped function and__original__
attribute referring to innermost wrapped one.Mostly used to create decorators:
def some_decorator(func): @wraps(func) def wrapper(*args, **kwargs): do_something(*args, **kwargs) return func(*args, **kwargs)
But see also
decorator()
for that.
-
unwrap
(func)¶ Get the object wrapped by
func
.Follows the chain of
__wrapped__
attributes returning the last object in the chain.
-
class
ContextDecorator
¶ A base class or mixin that enables context managers to work as decorators.