Decorators with Arguments

If decorators are to be configurable via additional decorator parameters, the static decoration scheme according to Pyc. 2 suggests the extended form,

Pyc. 4 Static decoration with decorator parameters
@Decorator(*deco_args, **deco_kwargs)
def function():
    pass                        # Some code ...

which is understood by the Python compiler in its dynamic form:

Pyc. 5 Dynamic decoration with decorator parameters
function = Decorator(*deco_args, **deco_kwargs)(function)

Pyc. 5 is a special case of the most general dynamic decoration scheme.

Pyc. 6 General dynamic decoration with decorator parameters as well as extra parameters
modified = Decorator(*deco_args, **deco_kwargs)(original, *args, **kwargs)

Therein original and modified stand respectively for a function or class. Both extra parameter arguments *args and **kwargs refer to the original, i.e. they define parameter values for an original function or for the initializer of the original class, respectively. Correspondingly, any direct class decoration like

Pyc. 7 Static decoration of a class
@Decorator(*deco_args, **deco_kwargs)
class Classname:
    def __init__(self, *args, **kwargs)
        pass                    # Some code ...

should be understood as decoration of the class initializer.

Pyc. 8 Static decoration of a class initializer
class Classname:
    @Decorator(*deco_args, **deco_kwargs)
    def __init__(self, *args, **kwargs)
        pass                    # Some code ...

On the other hand, the decorator parameter arguments *deco_args and **deco_kwargs are used to pass information to the decorator itself, e.g. to parameterize or configure the decorator.

Since the decoration of a class also refers to the class initializer, and thus to a function, a symbolic function is used below as an example representative of an arbitrary decoratored object.


◄ prev

up

next ►

Legal Notice

Privacy Policy

Cookie Consent

Sphinx 7.2.6 & Alabaster 0.7.12

© Copyright 2020-, Martin Abel, eVation. All Rights Reserved.