Create a Cappa command class (a dataclass) from a CommandInfo object.
Subcommands become nested command classes, collected in a subcommand field.
Parameters:
| Name |
Type |
Description |
Default |
cmd_info
|
CommandInfo
|
The CommandInfo object to convert
|
required
|
handler
|
Handler | None
|
Called by cappa.invoke with the invoked command's info and its
parsed values.
|
None
|
Returns:
| Type |
Description |
type[Any]
|
A dataclass decorated with cappa.command
|
Source code in src/clinspector/synthesis/synth_cappa.py
| def create_class(cmd_info: CommandInfo, handler: Handler | None = None) -> type[Any]:
"""Create a Cappa command class (a dataclass) from a CommandInfo object.
Subcommands become nested command classes, collected in a `subcommand` field.
Args:
cmd_info: The CommandInfo object to convert
handler: Called by `cappa.invoke` with the invoked command's info and its
parsed values.
Returns:
A dataclass decorated with cappa.command
"""
fields = [_create_field(p) for p in cmd_info.params if not is_help_param(p)]
# dataclasses require fields without defaults to come first
fields.sort(key=lambda f: _has_default(f[2]))
if cmd_info.subcommands:
sub_classes = [create_class(sub, handler) for sub in cmd_info.subcommands.values()]
union = functools.reduce(operator.or_, sub_classes)
hint = Annotated[union, cappa.Subcommand()] # ty: ignore[invalid-type-form]
fields.insert(0, ("subcommand", hint, dataclasses.field()))
cls = dataclasses.make_dataclass(_class_name(cmd_info.name), fields)
cls.__doc__ = cmd_info.description or None
invoke = None
if handler is not None:
def invoke(command: Any) -> Any:
values = {
f.name: getattr(command, f.name)
for f in dataclasses.fields(command)
if f.name != "subcommand"
}
return handler(cmd_info, values)
invoke.__annotations__ = {"command": cls} # cappa injects the parsed instance
return cappa.command( # ty: ignore[not-callable]
cls,
name=cmd_info.name,
help=cmd_info.description or None,
hidden=cmd_info.hidden,
deprecated=cmd_info.deprecated,
invoke=invoke,
)
|