Skip to content

Dependency Injection

arc supports a simple dependency injection system for commands.

examples/dependency.py
import arc


def dep(ctx: arc.Context) -> int:
    return 2


@arc.command()
def command(value: int = arc.Depends(dep)):
    arc.print(value)


command()
$ python dependency.py 
2

Note that arguments whose values are discovered via dependency injection do not have associated command line parameters. You can see this by inspecting the --help for the command.

$ python dependency.py --help
USAGE
    dependency.py [-h]

OPTIONS
    --help (-h)  Displays this help message
No value argument!

Type dependencies

A type can be denoted to be a dependency by implementing the __depends__() class method.

examples/type_dependency.py
import arc


class Dependency:
    def __init__(self, value: int) -> None:
        self.value = value

    @classmethod
    def __depends__(cls, ctx: arc.Context):
        return Dependency(2)


@arc.command()
def command(dep: Dependency):
    arc.print(dep)
    arc.print(dep.value)


command()
$ python type_dependency.py 
<Dependency object at 0x7ff8c63254e0>
2

Warning

If you implement this method, then this type cannot be used as the type of any other kind of parameter.

arc uses this feature to make various components available to your commands: