Skip to content

Classes as command groups

Pass a class (or an instance of one) to add_typer instead of a Typer sub-app. Each method decorated with @command(), without an app, becomes a command of the group. Methods without the decorator stay ordinary methods.

import typer

from typer_swissknife import add_typer, command


class Files:
    """Work with files."""

    @command()
    def copy(self, src: str, dst: str) -> None:
        """Copy a file."""

    @command(name="list", aliases=("ls",))
    def list_files(self) -> None:
        """List files."""

    def checksum(self, path: str) -> str:  # not a command
        ...


app = typer.Typer()
add_typer(app, Files)
$ python app.py files --help
 Work with files.
 Commands
  copy        Copy a file.
  list (ls)   List files.

$ python app.py files ls
  • The group is named after the class in kebab case (Files → files, UserRoles → user-roles). The class docstring is its help.
  • Every add_typer option works as usual: add_typer(app, Files, name="fs", aliases=("f",), ascii_name="Files").
  • Every command option works on a method: aliases, ascii_name, hidden, rich_help_panel, **kwargs for undeclared options, and so on.
  • @staticmethod and @classmethod can be commands too. Put @command() below them.
  • Commands from base classes come first, in definition order. Overriding a command without @command() removes it from the group.
  • add_typer returns the sub-app, so groups nest: add_typer(add_typer(app, Users), Roles).

Class or instance

You pass What happens
an instance, add_typer(app, Db(url)) every command uses that instance
the class, add_typer(app, Db) a new instance is created on every command call; the __init__ parameters become options of every command

Nothing is created when the app starts or when --help runs, only when a command runs.

class Db:
    """Database tools."""

    def __init__(self, url: str = typer.Option("sqlite:///app.db", "--url")) -> None:
        self.url = url

    @command()
    def migrate(self) -> None:
        print(f"migrating {self.url}")


add_typer(app, Db)
$ python app.py db migrate --url postgresql://localhost/app
migrating postgresql://localhost/app

Dependency injection with typer-di

With a typer-di TyperDI app, the built sub-app is a TyperDI too, so Depends(...) works in methods and in __init__. Injecting into __init__ gives every command the same session through self:

from typing import Annotated

import typer
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from typer_di import Depends, TyperDI

from typer_swissknife import add_typer, command


def get_session(db_url: str = typer.Option("sqlite:///app.db", "--db-url", envvar="DB_URL")) -> Session:
    return Session(create_engine(db_url))


def get_current_user(user: str = typer.Option("guest", "--user", "-u")) -> str:
    return user


class Users:
    """Manage users."""

    def __init__(
        self,
        session: Annotated[Session, Depends(get_session)],
        current_user: Annotated[str, Depends(get_current_user)],
    ) -> None:
        self.session = session
        self.current_user = current_user

    @command(name="list", aliases=("ls",))
    def list_users(self, active: bool = False) -> None:
        print(self.session.query(User).filter_by(active=active).all())

    @command()
    def add(self, name: str, **fields: str) -> None:
        self.session.add(User(name=name, created_by=self.current_user, **fields))
        self.session.commit()


app = TyperDI()
add_typer(app, Users)
$ python app.py users add bob -u admin --email bob@example.com --db-url postgresql://...
$ python app.py users add --help     # lists NAME, --db-url and --user / -u

Errors

Raised by add_typer (or by command()) when your code runs, not when users run the CLI:

Exception When
ValueError the class has no methods decorated with @command()
ValueError a method parameter has the same name as an __init__ parameter (class passed)
ValueError an __init__ parameter is *args or **kwargs, or a method parameter is positional-only or *args
TypeError @command() without an app decorates a function that is not a method