-
How do I go about doing this @dataclass
class BaseCommand:
host: Annotated[str | None, cappa.Arg(long="--host")]
def __call__(self, config: ConfigDep):
if self.host:
try:
host = config.hosts[self.host]
except KeyError as e:
raise cappa.Exit(f"Host {self.host} does not exist", code=1)
else:
host = config.primary_host
super().__call__(host) # noqa
@cappa.command(help="Run arbitrary command on the server")
class Exec(BaseCommand):
def __call__(self, config: ConfigDep):
print(self.host) The code above does not work, basically I need a |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
I assume the So the I would probably personally write it like this: from dataclasses import dataclass
from functools import cache
from typing import Annotated, ClassVar
import cappa
@dataclass(frozen=True)
class Config:
primary_host = "primary"
hosts: ClassVar = {"foo": "foo"}
ConfigDep = Annotated[Config, cappa.Dep(Config)]
@dataclass(frozen=True)
class BaseCommand:
_host: Annotated[str | None, cappa.Arg(long="--host")]
@cache
def host(self, config: ConfigDep):
if not self._host:
return config.primary_host
try:
return config.hosts[self._host]
except KeyError:
raise cappa.Exit(f"Host {self._host} does not exist", code=1)
@cappa.command(help="Run arbitrary command on the server")
class Exec(BaseCommand):
def __call__(self, config: ConfigDep, output: cappa.Output):
output.output(f"host: {self.host(config)}")
cappa.invoke(Exec) Basically just to localize the handling of |
Beta Was this translation helpful? Give feedback.
I assume the
primary_host
is not a static/env var? (if so, it could be a default on the cappa class itself)So the
super().__call__(host)
would need to be in theExec
impl in order to work properly, as written. at which point it seems to yield the behavior i'd think you would expect.I would probably personally write it like this: