API¶
This part of the documentation lists the full API reference of all public classes and functions. For more details refer to Click documentation
Decorators¶
- aclick.command(__func: Callable[[...], Any]) aclick.core.Command [source]¶
- aclick.command(name: Optional[str] = None, **attrs: Any) Callable[[...], aclick.core.Command]
- aclick.command(name: Optional[str] = None, cls: Type[aclick.decorators.CmdType] = None, **attrs: Any) Callable[[...], aclick.decorators.CmdType]
- aclick.command(name: Optional[str] = None, cls: Type[aclick.decorators.ClickCmdType] = None, **attrs: Any) Callable[[...], aclick.decorators.ClickCmdType]
Creates a new
Command
and uses the decorated function as callback. This will automatically parse the function signature (if no other signature is supplied) and generates Option and Argument instance accordingly. User can override individual parameters either by using click.option and click.argument decorators or by passing custom parameters with the same name as the parameters to override. The name of the command defaults to the name of the function with underscores replaced by dashes. If you want to change that, you can pass the intended name as the first argument. All keyword arguments are forwarded to the underlying command class. Once decorated the function turns into aCommand
instance that can be invoked as a command line utility or be attached to a commandGroup
.NOTE: This decorator should always be used instead of click command decorator, because in click, the help is automatically populated with the callback’s __doc__ and it is not parsed correctly.
- Parameters
name – the name of the command. This defaults to the function name with underscores replaced by dashes.
cls – the command class to instantiate. This defaults to
Command
. If the class is not a subclass ofCommand
, it is automatically wrapped.hierarchical – whether to parse complex types using hierarchical parsing instead of inline parsing. In hierarchical parsing the complex class options are expanded into individual options corresponding to individual properties. Note that some types are not supported with hierarchical parsing. Default is to use hierarchical parsing.
map_parameter_name – a function that maps from parameter paths (e.g. param1.property1.subproperty2) into parameter name used in parsing.
- aclick.group(__func: Callable[[...], Any]) aclick.core.Group [source]¶
- aclick.group(name: Optional[str] = None, **attrs: Any) Callable[[aclick.decorators.F], aclick.core.Group]
Creates a new
Group
with a function as callback. This works otherwise the same ascommand()
just that the cls parameter is set toGroup
.
- aclick.configuration_option(*param_decls: str, parse_configuration: Optional[Callable[[...], Dict[str, Any]]] = None, **kwargs: Any) Callable[[aclick.decorators.F], aclick.decorators.F] [source]¶
Add a
--configuration
option which allows to specify a configuration file to read the default configuration from.- Parameters
param_decls – One or more option names. Defaults to the single value
"--configuration"
.parse_configuration – Function used to parse configuration. By default a json parser is used.
kwargs – Extra arguments are passed to
option()
.
- aclick.utils.copy_signature(other_function: Callable, copy_return_annotation: bool = False) Callable[[aclick.utils.T], aclick.utils.T] [source]¶
This is a decorator used to copy signature from another function called inside this function. The parameters from the called function are added only if current function is able to receive them (it has either *args, or **kwargs argument. The signature is copied including the description of all parameters.
Example usage:
def a(param1: int): pass @copy_signature(a) def b(param2, *args, **kwargs): a(*args, **kwargs)
- Parameters
other_function – Signature to extend the current function with (i.e. the called function)
copy_return_annotation – Whether the return type annotation should be taken from the called function.
- aclick.utils.default_from_str() Callable[[aclick.utils.TType], aclick.utils.TType] [source]¶
- aclick.utils.default_from_str(cls: aclick.utils.TType) aclick.utils.TType
A decorator that extends the class with the
from_str()
,__str__()
, and__str_with_dashes_option__()
methods. Thefrom_str()
method is a classmethod and it parses a string value into the instance of the class. If some class derive this class, this class will be able to parse the string value as these instances as well. In this case,from_str()
should be called on this type (parent class).__str__()
and__str_with_dashes_option__()
are implemented as inverse offrom_str()
(i.e., the strings generated by these methods can be parsed usingfrom_str()
method).__str_with_dashes_option__()
further allows to specify if the underscores in class names and property names should be converted to dashes.Example usage:
@default_from_str class A: def __init__(self, prop1: int): self.prop1 = prop1 str(A(42)) == "a(prop1=42)"
Commands¶
- class aclick.Command(*args, signature: Optional[inspect.Signature] = None, hierarchical: bool = True, map_parameter_name: Optional[aclick.core.ParameterRenamer] = None, show_defaults: Optional[bool] = True, use_dashes: bool = True, num_inline_examples_help: int = 0, **kwargs)[source]¶
Command class extend click.Command class and it automatically parses callback’s signature and generates the parameters. It also supports dynamic parsing, where based on some parameter, other parameters may be added, which is used in the hierarchical parsing (see is_hierarchical).
- Parameters
name – the name of the command to use unless a group overrides it.
context_settings – an optional dictionary with defaults that are passed to the context object.
callback – the callback to invoke. This is optional.
signature – signature to be used for automatic parameter registration. If no signature is specified, it is parsed automatically from the callback.
hierarchical – whether to parse complex types using hierarchical parsing instead of inline parsing. In hierarchical parsing the complex class options are expanded into individual options corresponding to individual properties. Note that some types are not supported with hierarchical parsing. Default is to use hierarchical parsing.
map_parameter_name – a function that maps from parameter paths (e.g. param1.property1.subproperty2) into parameter name used in parsing.
params – the parameters to register with this command. This can be either
Option
orArgument
objects. These parameters override automatically generated params if they share the same name.help – the help string to use for this command. The callback’s docstring is parsed if no help is passed.
epilog – like the help string but it’s printed at the end of the help page after everything else.
short_help – the short help to use for this command. This is shown on the command listing of the parent command. The callback’s docstring is parsed if no help is passed.
show_defaults – whether to show defaults for all parameters. Default is
True
.use_dashes – use dashes instead of underscores in parameter and class names. Default is
True
.num_inline_examples_help – limits the number of examples to show in help for each inline type argument. If the value is -1, all possible values are shown. Default is 0.
add_help_option – by default each command registers a
--help
option. This can be disabled by this parameter.no_args_is_help – this controls what happens if no arguments are provided. This option is disabled by default. If enabled this will add
--help
as argument if no arguments are passedhidden – hide this command from help outputs.
deprecated – issues a message indicating that the command is deprecated.
- context_class[source]¶
alias of
aclick.core.Context
- invoke(ctx: click.core.Context) Any [source]¶
Given a context, this invokes the attached callback (if it exists) in the right way.
- make_context(*args, **kwargs)[source]¶
This function when given an info name and arguments will kick off the parsing and create a new
Context
. It does not invoke the actual command callback though.To quickly customize the context class used without overriding this method, set the
context_class
attribute.- Parameters
info_name – the info name for this invocation. Generally this is the most descriptive name for the script or command. For the toplevel script it’s usually the name of the script, for commands below it it’s the name of the command.
args – the arguments to parse as list of strings.
parent – the parent context if available.
extra – extra keyword arguments forwarded to the context constructor.
Changed in version 8.0: Added the
context_class
attribute.
- parse_args(ctx: click.core.Context, args: List[str]) List[str] [source]¶
Given a context and a list of arguments this creates the parser and parses the arguments, then modifies the context as necessary. This is automatically invoked by
make_context()
.
- class aclick.Group(name: Optional[str] = None, commands: Optional[Union[Dict[str, click.core.Command], Sequence[click.core.Command]]] = None, **attrs: Any)[source]¶
- command(__func: Callable[[...], Any]) aclick.core.Command [source]¶
- command(*args: Any, **kwargs: Any) Callable[[Callable[[...], Any]], aclick.core.Command]
A shortcut decorator for declaring and attaching a command to the group. This takes the same arguments as
command()
and immediately registers the created command with this group by callingadd_command()
. To customize the command class used, set thecommand_class
attribute.
- group(__func: Callable[[...], Any]) aclick.core.Group [source]¶
- group(*args: Any, **kwargs: Any) Callable[[Callable[[...], Any]], aclick.core.Group]
A shortcut decorator for declaring and attaching a group to the group. This takes the same arguments as
group()
and immediately registers the created group with this group by callingadd_command()
. To customize the group class used, set thegroup_class
attribute.
Types¶
- aclick.types.List = <class 'aclick.types.List'>[source]¶
This type parses a list of values separated by commas as individual instances. This type supports inline class parsing. A complicated structure of classes can be parsed using this type. See
parse_class_structure()
.- Parameters
inner_type – Type of the objects in the list.
- aclick.types.ClassUnion = <class 'aclick.types.ClassUnion'>[source]¶
This type parses the string value as the instance of one of specified classes. A complicated structure of classes can be parsed using this type. See
parse_class_structure()
.- Parameters
classes – List of classes to parse into.
known_classes – List of classes supported at deeper levels (e.g. as property values).
num_examples_on_error – Number of examples to show if there was an error during parsing. If the value is -1, all possible examples are shown. Default is 3.
- aclick.types.Tuple = <class 'aclick.types.Tuple'>[source]¶
The default behavior of Click is to apply a type on a value directly. This works well in most cases, except for when nargs is set to a fixed count and different types should be used for different items. In this case the
Tuple
type can be used. This type can only be used if nargs is set to a fixed number. This can be selected by using a Python tuple literal as a type.As opposed to Click’s original Tuple type, this type supports inline class parsing. A complicated structure of classes can be parsed using this type. See
parse_class_structure()
.- Parameters
types – a list of types that should be used for the tuple items.
- aclick.types.UnionTypeHierarchicalOption = <class 'aclick.types.UnionTypeHierarchicalOption'>[source]¶
Options are usually optional values on the command line and have some extra features that arguments don’t have.
All other parameters are passed onwards to the parameter constructor.
- Parameters
show_default – Show the default value for this option in its help text. Values are not shown by default, unless
Context.show_default
isTrue
. If this value is a string, it shows that string in parentheses instead of the actual value. This is particularly useful for dynamic options. For single option boolean flags, the default remains hidden if its value isFalse
.show_envvar – Controls if an environment variable should be shown on the help page. Normally, environment variables are not shown.
prompt – If set to
True
or a non empty string then the user will be prompted for input. If set toTrue
the prompt will be the option name capitalized.confirmation_prompt – Prompt a second time to confirm the value if it was prompted for. Can be set to a string instead of
True
to customize the message.prompt_required – If set to
False
, the user will be prompted for input only when the option was specified as a flag without a value.hide_input – If this is
True
then the input on the prompt will be hidden from the user. This is useful for password input.is_flag – forces this option to act as a flag. The default is auto detection.
flag_value – which value should be used for this flag if it’s enabled. This is set to a boolean automatically if the option string contains a slash to mark two options.
multiple – if this is set to True then the argument is accepted multiple times and recorded. This is similar to
nargs
in how it works but supports arbitrary number of arguments.count – this flag makes an option increment an integer.
allow_from_autoenv – if this is enabled then the value of this parameter will be pulled from an environment variable in case a prefix is defined on the context.
help – the help string.
hidden – hide this option from help outputs.
Changed in version 8.1.0: Help text indentation is cleaned here instead of only in the
@option
decorator.Changed in version 8.1.0: The
show_default
parameter overridesContext.show_default
.Changed in version 8.1.0: The default of a single option boolean flag is not shown if the default value is
False
.Changed in version 8.0.1:
type
is detected fromflag_value
if given.
- aclick.types.OptionalTypeHierarchicalOption = <class 'aclick.types.OptionalTypeHierarchicalOption'>[source]¶
Options are usually optional values on the command line and have some extra features that arguments don’t have.
All other parameters are passed onwards to the parameter constructor.
- Parameters
show_default – Show the default value for this option in its help text. Values are not shown by default, unless
Context.show_default
isTrue
. If this value is a string, it shows that string in parentheses instead of the actual value. This is particularly useful for dynamic options. For single option boolean flags, the default remains hidden if its value isFalse
.show_envvar – Controls if an environment variable should be shown on the help page. Normally, environment variables are not shown.
prompt – If set to
True
or a non empty string then the user will be prompted for input. If set toTrue
the prompt will be the option name capitalized.confirmation_prompt – Prompt a second time to confirm the value if it was prompted for. Can be set to a string instead of
True
to customize the message.prompt_required – If set to
False
, the user will be prompted for input only when the option was specified as a flag without a value.hide_input – If this is
True
then the input on the prompt will be hidden from the user. This is useful for password input.is_flag – forces this option to act as a flag. The default is auto detection.
flag_value – which value should be used for this flag if it’s enabled. This is set to a boolean automatically if the option string contains a slash to mark two options.
multiple – if this is set to True then the argument is accepted multiple times and recorded. This is similar to
nargs
in how it works but supports arbitrary number of arguments.count – this flag makes an option increment an integer.
allow_from_autoenv – if this is enabled then the value of this parameter will be pulled from an environment variable in case a prefix is defined on the context.
help – the help string.
hidden – hide this option from help outputs.
Changed in version 8.1.0: Help text indentation is cleaned here instead of only in the
@option
decorator.Changed in version 8.1.0: The
show_default
parameter overridesContext.show_default
.Changed in version 8.1.0: The default of a single option boolean flag is not shown if the default value is
False
.Changed in version 8.0.1:
type
is detected fromflag_value
if given.
Utilities¶
- aclick.utils.parse_class_structure(value: str, classes: List[Type], known_classes: Optional[List[Type]] = None) Any [source]¶
Parses a string representing a structure of classes into a tree representation of the classes. This method is directly used by the
default_from_str()
decorator.The following conventions are used:
Classes are represented as class_name(arg1, arg2, named_arg1=val3, …)
Lists are represented as [val1, val2, …]
Tuples are represented as (val1, val2, …)
Dicts are represented as {key1=val1, key2=val2, …}
Strings can be represented as value or “complicated ‘value’” or ‘complicated “value”’
Numbers and bool are represented as strings: 15, 16.2, true
- Parameters
value – String value to parse.
classes – List of classes to parse the string into.
known_classes – List of known classes that can be used during parsing on lower levels (e.g. as a property value).
- Returns
An instance of one of the classes is returned.
- aclick.utils.as_dict(obj: Any, tp: Optional[Type] = None) Any [source]¶
Returns a dictionary where all classes in the class structure are replaced with simple dictionaries. It can be useful for serilization.
This performs the inverse operation to
from_dict()
. Note that iftp
is not a class the returned value may not be a dictionary but any value.- Parameters
obj – value that is used to generate the dictionary.
tp – type of the passed object. If no type is passes, the actual type of
obj
is used.
Configuration¶
- aclick.parse_configuration(fp, *, ctx: aclick.core.Context)[source]¶
Parses the configuration file using one of the supported configuration providers.
- Parameters
fp – opened configuration file stream
ctx – context providing additional information used for parsing
- aclick.register_configuration_provider(regex: str) Callable[[aclick.configuration.TConfigurationProvider], aclick.configuration.TConfigurationProvider] [source]¶
A decorator that registers a new configuration provider.
- Parameters
regex – Regex expression that matches the supported filenames.
- aclick.configuration.restrict_parse_configuration(path: str, parse_configuration: Optional[aclick.configuration.ConfigurationProvider] = None) aclick.configuration.ConfigurationProvider [source]¶
Restrict the parse_configuration function to a specific path. This is useful if your function takes a shared parameter of specific class for which you want to store the configuration.
- Parameters
path – path to the parameter for which you want to parse the configuration.
parse_configuration – parse_configuration function that will be used for parsing. Default is to use the registered configuration providers.
- aclick.configuration.parse_json_configuration(fp, *, ctx: aclick.core.Context)[source]¶
Loads a configuration stored in a json file
- Parameters
fp – opened json file stream
ctx – context providing additional information used for parsing
- aclick.configuration.parse_yaml_configuration(fp, *, ctx: aclick.core.Context)[source]¶
Loads a configuration stored in a yaml (.yaml or .yml) file
- Parameters
fp – opened yaml file stream
ctx – context providing additional information used for parsing
- aclick.configuration.parse_gin_configuration(fp, *, ctx: aclick.core.Context)[source]¶
Loads a configuration stored as a gin config file
- Parameters
fp – opened gin file stream
ctx – context providing additional information used for parsing
Other classes¶
- class aclick.ParameterRenamer[source]¶
A base class used as parameter renamer for a
Command
. The derived class must implement the call method that maps from the original name to a new name.
- class aclick.RegexParameterRenamer(patterns: List[Tuple[str, str]])[source]¶
The
RegexParameterRenamer
replaces parameter name using regex matching and substitution. The first pattern that matches the parameter name is used and the matched part of the parameter name is substituted with the replacement value. If no regex expression matches the parameter name, the name is returned unchanged.- Attr patterns
List of pairs of patterns and replacement values.
- class aclick.FlattenParameterRenamer(num_levels: int = - 1)[source]¶
The
FlattenParameterRenamer
is used to map parameters into lower level parameters (e.g. “class1.prop1” into “prop1”). This is especially useful for hierarchical parsing, where properties deep in the class structure can have long names. The number of levels to remove is a parameter of the class.