Transforms a flat wrapper into a decorator with or without arguments. @decorator passes special call 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:

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:

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)

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:

def with_phone(call):
    # ...
    return call(phone=phone)

def with_user(call):
    # ...
    return call(user=user)

def some_view(request, phone=None, user=None):
    # ...
    return # ...

If a function wrapped with @decorator has arguments other than call, then decorator with arguments is created:

def joining(call, sep):
    return sep.join(call())

You can see more examples in flow and debug submodules source code.


A decorator helping to create context managers. Resulting functions also behave as decorators.

A simple example:

def tag(name):
    print "<%s>" % name,
    print "</%s>" % name

with tag("h1"):
    print "foo",
# -> <h1> foo </h1>

Using as decorator:

def shout(text):
    print text.upper()

# -> <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):
    def wrapper(*args, **kwargs):
        do_something(*args, **kwargs)
        return func(*args, **kwargs)

But see also @decorator for that. This is extended version of functools.wraps().


Get the object wrapped by func.

Follows the chain of __wrapped__ attributes returning the last object in the chain.

This is a backport from python 3.4.

class ContextDecorator

A base class or mixin that enables context managers to work as decorators.