API Reference¶
Everything documented on this page can be imported from cotyper directly. Other modules
are internal and may change without notice.
Building CLIs¶
cotyper.App
¶
Bases: Typer
A typer.Typer whose struct_commands take pydantic models as parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
Any
|
passed on to |
()
|
env_prefix
|
str | None
|
when set, every |
None
|
**kwargs
|
Any
|
passed on to |
{}
|
struct_command(name=None, *, add_config_file_option=None, default_config_files=(), add_print_config_option=None, wraps_command=None, **command_kwargs)
¶
Register a command whose (nested) pydantic model parameters become options.
Works like typer.Typer.command, but each model parameter foo is unfolded
into --foo-... options; the models are rebuilt before the function is called.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
name of the command exposed to the CLI |
None
|
add_config_file_option
|
str | None
|
name of an extra option that loads the command's
parameters from a config file or an inline JSON string, e.g.
|
None
|
default_config_files
|
Sequence[str | Path]
|
config files tried in order when the config-file
option is not given (needs |
()
|
add_print_config_option
|
str | None
|
name of an extra flag that prints the effective
configuration as JSON and exits, e.g. |
None
|
wraps_command
|
tuple[str, str] | None
|
deprecated, has no effect and will be removed |
None
|
**command_kwargs
|
Any
|
passed on unchanged to |
{}
|
Returns:
| Type | Description |
|---|---|
Callable[[CommandFunctionType], CommandFunctionType]
|
the decorator registering the command |
command(name=None, *, add_config_file_option=None, default_config_files=(), wraps_command=None, **command_kwargs)
¶
typer.Typer.command, plus the optional config-file option.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
name of the command exposed to the CLI |
None
|
add_config_file_option
|
str | None
|
see |
None
|
default_config_files
|
Sequence[str | Path]
|
see |
()
|
wraps_command
|
tuple[str, str] | None
|
deprecated, has no effect and will be removed |
None
|
**command_kwargs
|
Any
|
passed on unchanged to |
{}
|
Returns:
| Type | Description |
|---|---|
Callable[[CommandFunctionType], CommandFunctionType]
|
the decorator registering the command |
register_type_processor(predicate, processor)
¶
Handle a custom field type in this app's struct_commands.
Processors registered later take precedence, and all of them are tried
before the built-in ones. Register before decorating the commands that
use the type. Other App instances (including sub-apps added with
add_typer) are not affected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predicate
|
Callable[[Any], bool]
|
returns True for the annotations |
required |
processor
|
Callable[[Any], TypeProcessingResult]
|
turns such an annotation into a |
required |
cotyper.unfold_cls(*cls)
¶
cotyper.parse_json_fields(*field_type)
¶
decorator function to add a dynamic validator to a pydantic BaseModel such that it will parse a json dict string to correct type.
Example usage:
class Bar(BaseModel):
baz: str
@parse_json_fields((["bar", "baz"], Bar), ("foobar", Bar))
class Foo(BaseModel):
bar: Bar
baz: Bar
foobar: List[Bar]
foo = Foo(bar='{"baz":"baz"}', baz='{"baz":"bar"}', foobar=['{"baz":"foobar"}'])
Returns:
| Type | Description |
|---|---|
Callable[[type[BaseModel]], type[BaseModel]]
|
wrapped BaseModel class object |
Custom types¶
See Custom types in the guide for an example.
cotyper.TypeProcessingResult
dataclass
¶
How a field type becomes a CLI option; returned by a type processor.
Attributes:
| Name | Type | Description |
|---|---|---|
annotation |
TypeAnnotation
|
the annotation Typer sees for the option |
callback |
Callable | None
|
Typer option callback, run after parsing |
parser |
Callable[[str], TypeAnnotation] | None
|
turns the raw command-line string into a value |
click_type |
ParamType | None
|
a ParamType that converts the raw value; use it instead of |
doc_suffix |
str
|
appended to the option's help text, e.g. |
cotyper.register_type_processor(predicate, processor)
¶
Register a new type processor for custom types, for every App in the process.
Prefer App.register_type_processor, which only affects that app. Processors
registered here are tried after an app's own and before the built-in ones.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predicate
|
Callable[[TypeAnnotation], bool]
|
Function that returns True if the processor should handle this type |
required |
processor
|
Callable[[TypeAnnotation], TypeProcessingResult]
|
Function that processes the type and returns TypeProcessingResult |
required |
Errors¶
These are raised while the CLI is being built, for a command or model CoTyper cannot handle.
Invalid values typed on the command line are reported by Typer as usage errors (exit code 2).
Each error also subclasses the built-in exception it used to be (TypeError/ValueError).
cotyper.CotyperError
¶
Bases: Exception
Base class for all errors cotyper raises on purpose.
cotyper.UnsupportedTypeError
¶
Bases: CotyperError, TypeError, ValueError
A type annotation cotyper cannot turn into command-line options.
Also a TypeError and a ValueError: before this class existed, such
errors were raised as one or the other.
cotyper.DefinitionError
¶
Bases: CotyperError, ValueError
A command, model or option definition cotyper cannot build a CLI from.
For example: two parameters flattening to the same option name, or a
field that needs parse_json_fields but does not have it.
Logging¶
See Logging in the guide.
cotyper.configure_logging(cfg=None)
¶
Opt in to cotyper's logging setup. Call it from your application, not a library.
Without cfg the settings are read from, in increasing priority, the
defaults, a TOML file (COTYPER_LOG_CONFIG or ./cotyper_log.toml) and
the LOG_LEVEL/LOG_BACKEND/LOG_LEVEL_WARNING_MODULES env vars.
The plain and rich backends configure the root logger (rich also
installs rich's traceback handler); loguru replaces loguru's sinks and
forwards cotyper's records to it. Returns the cotyper logger, or the
loguru logger for the loguru backend.
cotyper.LogConfig
¶
Bases: BaseModel
Settings for configure_logging.
Attributes:
| Name | Type | Description |
|---|---|---|
level |
str
|
log level name, e.g. |
backend |
Literal['plain', 'rich', 'loguru']
|
|
format |
str
|
log format for the |
warning_modules |
list[str]
|
loggers limited to |