Pre-processing of some options #162
Replies: 2 comments 12 replies
-
I tend to do this sort of stuff in invoke dependencies from __future__ import annotations
from dataclasses import dataclass
from typing import Annotated as An
from typing import Literal
import cappa
def process(command: Command):
print(f"configure_logging: {command.log_level}")
@dataclass(kw_only=True)
class Command:
log_level: An[Literal["TRACE", "DEBUG"], cappa.Arg(short="-L")] = "INFO"
subcommands: cappa.Subcommands[Foo | Bar]
@dataclass
class Foo:
def __call__(self):
print("foo")
@dataclass
class Bar:
def __call__(self):
print("bar")
cappa.invoke(Command, deps=[process]) If there's a direct dependence on the output in downstream deps, you can just depend on them directly, or if (with logging) you'd want to do it on all subcommands regardless of context, and dont want to explicitly call out to it in each command's impl. Not relevant to this example, but something that occurs to me. Although a potential drawback here is if the dep is only utilized in a subset of commands (e.g. |
Beta Was this translation helpful? Give feedback.
-
I simplified things a bit: @dataclass(kw_only=True)
class CommonOptions(LogLevelPathOptions, ConfPathOption, HelpOption):
"""Common options for all commands."""
@dataclass(kw_only=True)
class BaseCommand(CommonOptions):
"""Base command class."""
def run(self) -> int:
"""Run the command."""
raise NotImplementedError
def __call__(self) -> int: # noqa: D102
configure_logging(self.log_level, self.log_path, allow="pypiserver")
return self.run() Now each command inherits from Why the |
Beta Was this translation helpful? Give feedback.
-
I'm rewriting an argparsed-based CLI with Cappa. In the previous
main
function, I was first parsing arguments into an argparse namespace, then using some options of this namespace to configure logging.After a bit of twiddling, here's how I achieved the same thing with Cappa:
And my
main
function doesn't have to do any special processing itself:Beta Was this translation helpful? Give feedback.
All reactions