Skip to content

Command Decorators

An arc decorator is a Python deocrator that wraps the execution of an arc command. They allow shared setup / teardown logic to be abstracted and re-used at will.

Example

examples/decorator_create.py
import arc


@arc.decorator()
def cb():
    arc.print("before execution")
    yield
    arc.print("after execution")


@cb
@arc.command()
def command():
    arc.print("command execution")


command()
$ python decorator_create.py 
before execution
command execution
after execution

Decorator Inheritance

By default, subcommands inherit their parent's decorators.

examples/decorator_inherit.py
import arc


@arc.decorator(children_only=True)
def cb():
    arc.print("-------before execution-------")
    yield
    arc.print("-------after execution-------")


@cb
@arc.command()
def command():
    ...


@command.subcommand()
def sub():
    arc.print("Execution")


command()
$ python decorator_inherit.py 
USAGE
    decorator_inherit.py [-h]
    decorator_inherit.py <subcommand> [ARGUMENTS ...]

decorator_inherit.py --help for more information
$ python decorator_inherit.py sub
-------before execution-------
Execution
-------after execution-------
What's children_only?

This makes the decorator only be executed when running a child of the command it decorates, and not the command itself. This is especially useful with the root command object because by default, any decorator that decorates it (with inheritance on) will be executed twice: once for the global callback, and once fot the actual command's callback.

If this behavior is undesired, the decorator can be made non-inhertibale by setting inherit=False

import arc

@arc.decorator(inherit=False)
def cb():
    arc.print("before execution")
    yield
    arc.print("after execution")
This decorator must be applied explicitly to all commands it should wrap

Alternativley, a decorator can be removed from a single subcommand (and any of it's children) by decorating the subcommand with @decorator.remove