6.4. Decorator Wrapper
Wrapper function
Wrapper lambda
Wrapper class
Wrapper method
6.4.1. Name
Name
wrapper
is just a convention
>>> def mydecorator(obj):
... def wrapper():
... ...
... return wrapper
>>> def mydecorator(obj):
... def wrap():
... ...
... return wrap
Underscore _
is a normal identifier name which can be used as a wrapper
name. Note, that this is a bit less readable than previous examples:
>>> def mydecorator(obj):
... def _():
... ...
... return _
6.4.2. Wrapper Function
obj
is a decorated objectDoesn't matter, whether is a function, class or method
>>> def mydecorator(obj):
... def wrapper(*args, **kwargs):
... ...
... return wrapper
6.4.3. Wrapper Lambda
obj
is a decorated objectDoesn't matter, whether is a function, class or method
>>> def mydecorator(obj):
... return lambda *args, **kwargs: obj(*args, **kwargs)
6.4.4. Wrapper Class
If
obj
andWrapper
are classes,Wrapper
can inherit fromobj
(to extend it)
>>> def mydecorator(obj):
... class Wrapper:
... def __init__(self, *args, **kwargs):
... ...
... return Wrapper
>>> def mydecorator(obj):
... class Wrapper(obj):
... def __init__(self, *args, **kwargs):
... ...
... return Wrapper
6.4.5. Wrapper Arguments
If you know names of the arguments you can use it in wrapper
args
arbitrary number of positional argumentskwargs
arbitrary number of keyword arguments
>>> def mydecorator(obj):
... def wrapper(a, b):
... return func(a, b)
... return wrapper
Positional Arguments:
>>> def mydecorator(obj):
... def wrapper(*args):
... return func(*args)
... return wrapper
Keyword Arguments:
>>> def mydecorator(obj):
... def wrapper(**kwargs):
... return func(**kwargs)
... return wrapper
Positional and Keyword Arguments:
>>> def mydecorator(obj):
... def wrapper(*args, **kwargs):
... return func(*args, **kwargs)
... return wrapper