Decorators¶
The four main decorators are the public surface of pyclifer. They wrap Click objects with framework features: automatic configuration, global option propagation, Rich logging, and standardized response handling.
app_group¶
Entry point decorator. Creates the root CLI group with all framework features enabled.
Key parameters:
context_factory— callable that receives allcontext=Trueoption values as keyword arguments and returns thectx.objinstance. Enables declarative context construction without a manualctx.obj =assignment in the group callback.context_options_panel— label for the help section that listscontext=Trueoptions in subcommand--helpoutput. Defaults to"Context Options (anywhere-passable)". Set to any string to customise the heading.auto_envvar_prefix— uppercase prefix for automatic environment variable binding. Withauto_envvar_prefix="MYAPP",--database-urlreadsMYAPP_DATABASE_URL.show_envvar—Trueby default. Set it toFalseto stop the help from listing the environment variables of the automatic options (--output-format,--config,--verbosity,--log-file,--time). The variables still work. Options you declare with@optionkeep their ownshow_envvarargument.sensitive_fields— field names to mask in log records on top of the defaults (password,token,secret, ...).enable_secrets_filter=Falseturns the filter off.mask_free_text—Falseby default. Also maskskey=valuepairs written inside the text of a log message and of the exceptions it carries. See Masking Free Text for what it finds and its limits.replace_root_handlers—Falseby default. pyclifer then replaces only its own console handler and keeps the handlers other libraries put on the root logger, except the console handler thatlogging.basicConfig()installs with its default arguments. Set it toTrueto remove them all. See Handlers From Other Libraries.version— the text--versionprints, for exampleversion="2.5.0". It needs the option: withadd_version_option=False, or on a@groupthat does not setadd_version_option=True, it raisesValueError.add_version_option=Falseremoves--version, andadd_verbosity_option=Falseremoves--verbosity.rich_help_config—RichHelpConfigurationinstance (or dict) forwarded to rich-click. Lets you customise colours, column widths, and panel styles in--helpoutput.use_rich_help— set toFalseto disable rich-click rendering and use plain Click help. Defaults toTrue. It is a choice of the whole application: the subgroups and commands built bygroup()andcommand()print plain help too once they are attached to it, and so do their usage errors. It only changes how the help is drawn: the group exposes the same options either way, and click-extra's own default options (--color,--theme,--show-params, ...) are not added. Passparams=[...]to add options of your own.handle_response—Trueby default on an application: every command returning aResponsehas it printed in the output format.Falseopts the application out. SeeHandleResponseMixinfor the three values and how a sub-group inherits or opts out.on— mapping of lifecycle event names to lists of handler functions, for exampleon={"config.loaded": [check_config]}. Keys are framework event names orEventobjects; a plain string that is not a framework event raisesValueErrorat decoration time. See the Lifecycle events guide.groupaccepts it too.
pyclifer.app_group(**kwargs)
¶
Decorator for the main CLI application entry point.
Enables all automatic features (config, logging, version, etc.) by default. Options like --verbosity will be propagated to all subcommands.
All keyword arguments map to GroupConfig fields or are forwarded to Click.
Notable options:
handle_response(bool): intercept and printResponseobjects automatically. Defaults to True on an application;Falseprotects the whole group from the propagation.timer(bool): inject--time/--no-time. Prints elapsed time in rich/table/raw; injectsexecution_timeandexecution_time_strintoResponse.datain json/yaml.output_format_default(str): the format the whole application answers in (json, yaml, table, rich, raw, text). It is the default of--output-format, and the fixed format when the option is not exposed. Any other value raises ValueError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Any
|
GroupConfig fields or Click group arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[..., Any]], Group]
|
A decorator that wraps the function as a pyclifer CLI group. |
Source code in src/pyclifer/core/decorators.py
group¶
Creates a subgroup that inherits global options from its parent. Its handle_response is None
by default: it follows the application once attached. handle_response=False protects its commands.
A subgroup never sets the logging up: only @app_group does, so the groups can be declared in any
order (cli.py imports its subgroups before it writes @app_group()). A @group() used without an
@app_group has no logging configured.
pyclifer.group(**kwargs)
¶
Decorator for CLI subgroups.
Creates a standard group without global application options by default.
Source code in src/pyclifer/core/decorators.py
command¶
Creates a CLI command. Use inside a group or app_group.
Key parameter:
handle_response=False— whenTrue, wraps the command withreturns_responseso anyResponsereturned by the function is printed automatically. Equivalent to stacking@returns_responsemanually.
pyclifer.command(name=None, handle_response=False, **kwargs)
¶
Create a Click command with optional automatic response handling.
When handle_response=True, any Response returned by the command function is automatically printed using the output format resolved from ctx.meta (--output-format option). This is equivalent to manually applying the returns_response decorator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
Name of the command. |
None
|
handle_response
|
bool
|
If True, wrap the function with returns_response. |
False
|
**kwargs
|
Any
|
Additional arguments passed to click_extra.command(). |
{}
|
Returns:
| Type | Description |
|---|---|
Callable[[_F], Command]
|
Decorated function as a Click command. |
Source code in src/pyclifer/core/decorators.py
option¶
Extends Click options with environment variable binding and optional global/context propagation.
is_global=True— propagates this option to all subcommands (seeGlobalOptionsMixin).context=True— marks this option as a context option: its value feedscontext_factoryand is accepted at any position in the command chain (see Anywhere-passable options). By default it also appears in subcommand--helpunder the Context Options panel.show_in_subcommand_help=True— whencontext=True, controls whether the option is shown in subcommand help. Set toFalseto hide it from subcommand help while keeping the anywhere-passable behaviour intact.store_in_meta=False— whenTrue, stores the option value inctx.metaautomatically (key:"pyclifer.<option-name>"). The option is not exposed as a function parameter. Used internally bypagination_optionsfor--pageand--limit.cls=...— the option class. It defaults toPycliferOption. Anyclick_extra.Optionsubclass works, such asTimerOption; it receives only the arguments its constructor declares. Asking such a class foris_global=TrueraisesTypeError, because onlyPycliferOptionsubclasses,CustomConfigOptionandPycliferVerbosityOptioncan be propagated. A subclass of one of them that only forwards**kwargsto its parent is accepted: the constructors of the whole MRO are searched foris_global.
pyclifer.option(*param_decls, is_global=False, context=False, show_envvar=True, store_in_meta=False, show_in_subcommand_help=True, **kwargs)
¶
Create a Click option with global propagation support.
Ensures a consistent environment variable display and allows options to be marked as global to be available on all subcommands.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*param_decls
|
str
|
Parameter declarations for the option. |
()
|
is_global
|
bool
|
If True, the option is propagated to all subcommands. |
False
|
context
|
bool
|
If True, the option feeds ctx.obj construction and is accepted at any position in the command chain. |
False
|
show_envvar
|
bool
|
Show environment variables in the help output. |
True
|
store_in_meta
|
bool
|
If True, stores the option value in ctx.meta automatically. |
False
|
show_in_subcommand_help
|
bool
|
If True, display-only copy of the option appears in subcommand help when context=True. |
True
|
**kwargs
|
Any
|
Additional arguments passed to click_extra.option(). |
{}
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable], Callable]
|
Option decorator function. |
Source code in src/pyclifer/core/decorators.py
output_filter_option¶
Adds --output-format to a command (JSON, YAML, Table, Rich, Raw).
pyclifer.output_filter_option(*param_decls, show_envvar=True, **kwargs)
¶
Add an output filter option to a command.
When combined with --output-format raw, json, or yaml, this option lets users extract a value from the Response data using a dotted key path.
The selected path is stored in ctx.meta['pyclifer.output_filter'] and is automatically picked up by returns_response.
Numeric path segments are treated as list indices. Resolution order: data["data"] first, then top-level response fields.
Example:
@app.command()
@output_filter_option()
@returns_response
@click.pass_context
def articles(ctx):
return Response(
success=True,
message="2 articles",
data={"results": [{"id": 1, "title": "Hello"}, {"id": 2}]},
)
# myapp articles -o raw -f results.0.title -> Hello
# myapp articles -o json -f results.0 -> {"id": 1, "title": "Hello"}
# myapp articles -o raw -f message -> 2 articles
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*param_decls
|
str
|
Parameter declarations (default: --output-filter, -f). |
()
|
show_envvar
|
bool
|
Show environment variables in the help output. |
True
|
**kwargs
|
Any
|
Additional arguments passed to the option decorator. |
{}
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable], Callable]
|
The decorated function. |
Source code in src/pyclifer/core/decorators.py
returns_response¶
Decorator that intercepts a Response return value and dispatches it to the formatter.
Applied automatically for all commands under @app_group (on by default). Use handle_response=False on the group or individual commands to opt out.
pyclifer.returns_response(f)
¶
Decorator that intercepts a Response return value and prints it automatically.
When the decorated command function returns a Response instance, this decorator reads the output format stored in ctx.meta['pyclifer.output_format'] (set by the --output-format option) and dispatches printing via BaseContext. Non-Response return values are left untouched.
Example:
@app.command()
@returns_response
@option("--name", default="world")
@click.pass_context
def hello(ctx, name):
return Response(success=True, message=f"Hello {name}", data={"name": name})
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
f
|
Callable
|
The command function to wrap. |
required |
Returns:
| Type | Description |
|---|---|
Callable
|
The wrapped function. |
Source code in src/pyclifer/core/decorators.py
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 | |
pagination_options¶
Injects --page and --limit options into a command. Values are stored in
ctx.meta["pyclifer.page"] and ctx.meta["pyclifer.limit"] via store_in_meta.
pyclifer.pagination_options(default_limit=20, max_limit=100)
¶
Inject --page and --limit options into a command.
Options are stored in ctx.meta under the keys 'pyclifer.page' and 'pyclifer.limit' via store_in_meta.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
default_limit
|
int
|
Default number of results per page. |
20
|
max_limit
|
int
|
Maximum allowed value for --limit (enforced via IntRange). |
100
|
Returns:
| Type | Description |
|---|---|
Callable[[_F], _F]
|
A decorator that adds --page and --limit to the decorated function. |