Skip to content

Callbacks

Sean Collings edited this page Jun 28, 2021 · 1 revision

The callback system provides an easy way to:

  • Share logic between commands
  • Perfrom validation on input data
  • Modify data before sending it to the function

Creating a callback

Callbacks are created by using special decorators exported by arc.callbacks these are:

  • before - Executed before the command executes, recieves all the arguments to be sent to the command as an argument
  • after - Executed after the command executes, recieves the return value of the command
  • around - Executes both before and after the command via the yield keyword.

After creating the callback with the specific decorator, it can be added to a command simply by decorating that command with it.

from arc import CLI, callbacks

@callbacks.before
def before_example(arguments):
    print("I'm executing before")

@callbacks.after
def after_example(val):
    print("I'm executing after")

@callbacks.around
def around_example(arguments):
    print("I'm starting now")
    yield
    print("I'm ending now")


cli = CLI()

@before_example
@after_example
@around_example
@cli.command()
def command():
    print("Hello there!")

cli()

If you execute this, you should see something similar to:

$ python3 example.py command
I'm executing before <------ before_example()
I'm starting now  < ----------------
Hello there! <---- the Command     | - around_example()
I'm ending now <--------------------
I'm executing after <------ after_example()

Clone this wiki locally