cloup.constraints¶
Constraints for parameter groups.
Added in version v0.5.0.
Submodules¶
Classes¶
|
Checks one constraint or another depending on the truth value of the condition. |
|
Satisfied if the number of set parameters is <= n. |
|
Satisfied if the number of set parameters is between |
|
It's satisfied if all operands are satisfied. |
A constraint that can be checked against an arbitrary collection of CLI parameters with respect to a specific |
|
|
|
|
Base class for all n-ary operators defined on constraints. |
|
It's satisfied if at least one of the operands is satisfied. |
|
A constraint decorator that can override the help and/or the error message of the wrapped constraint. |
Satisfied if the number of set parameters is >= n. |
|
Requires an exact number of parameters to be set. |
|
|
Abstract class that wraps another constraint and delegates all methods to it. |
|
A NamedTuple storing a |
|
Provides support for constraints. |
|
True if all listed parameters are set. |
|
True if any of the listed parameters is set. |
|
True if the parameter value equals |
|
True if the parameter is set. |
|
Logical NOT of a predicate. |
Functions¶
|
Return a decorator that adds the given parameters and applies a constraint to them. Equivalent to::. |
|
Register a constraint on a list of parameters specified by (destination) name (e.g. the default name of |
Attributes¶
Satisfied if none of the parameters is set. Useful only in conditional constraints. |
|
Satisfied if either all or none of the parameters are set. |
|
Satisfied if at most one of the parameters is set. |
|
Satisfied if all parameters are set. |
|
Alias for |
|
Alias for |
Contents¶
- class cloup.constraints.If(condition, then, else_=None)[source]¶
Bases:
cloup.constraints._core.ConstraintChecks one constraint or another depending on the truth value of the condition.
Added in version 0.8.0: you can now pass a sequence of parameter names as condition, which corresponds to the predicate
AllSet(*param_names).- Parameters:
condition (str | Sequence[str] | Predicate) – can be either an instance of
Predicateor (more often) the name of a parameter or a list/tuple of parameters that must be all set for the condition to be true.then (Constraint) – a constraint checked if the condition is true.
else – an (optional) constraint checked if the condition is false.
else_ (Constraint | None)
- help(ctx)[source]¶
A description of the constraint.
- Parameters:
ctx (click.Context)
- Return type:
str
- check_consistency(params)[source]¶
Perform some sanity checks that detect inconsistencies between these constraints and the properties of the input parameters (e.g. required).
For example, a constraint that requires the parameters to be mutually exclusive is not consistent with a group of parameters with multiple required options.
These sanity checks are meant to catch developer’s mistakes and don’t depend on the values assigned to the parameters; therefore:
they can be performed before any parameter parsing
they can be disabled in production (setting
check_constraints_consistency=Falseincontext_settings)
- Parameters:
params (Sequence[click.Parameter]) – list of
click.Parameterinstances- Raises:
UnsatisfiableConstraintif the constraint cannot be satisfied independently from the values provided by the user- Return type:
None
- check_values(params, ctx)[source]¶
Check that the constraint is satisfied by the input parameters in the given context, which (among other things) contains the values assigned to the parameters in
ctx.params.You probably don’t want to call this method directly. Use
check()instead.- Parameters:
params (Sequence[click.Parameter]) – list of
click.Parameterinstancesctx (click.Context) –
click.Context
- Raises:
- Return type:
None
- class cloup.constraints.AcceptAtMost(n)[source]¶
Bases:
ConstraintSatisfied if the number of set parameters is <= n.
- Parameters:
n (int)
- max_num_params¶
- help(ctx)[source]¶
A description of the constraint.
- Parameters:
ctx (click.Context)
- Return type:
str
- check_consistency(params)[source]¶
Perform some sanity checks that detect inconsistencies between these constraints and the properties of the input parameters (e.g. required).
For example, a constraint that requires the parameters to be mutually exclusive is not consistent with a group of parameters with multiple required options.
These sanity checks are meant to catch developer’s mistakes and don’t depend on the values assigned to the parameters; therefore:
they can be performed before any parameter parsing
they can be disabled in production (setting
check_constraints_consistency=Falseincontext_settings)
- Parameters:
params (Sequence[click.Parameter]) – list of
click.Parameterinstances- Raises:
UnsatisfiableConstraintif the constraint cannot be satisfied independently from the values provided by the user- Return type:
None
- check_values(params, ctx)[source]¶
Check that the constraint is satisfied by the input parameters in the given context, which (among other things) contains the values assigned to the parameters in
ctx.params.You probably don’t want to call this method directly. Use
check()instead.- Parameters:
params (Sequence[click.Parameter]) – list of
click.Parameterinstancesctx (click.Context) –
click.Context
- Raises:
- Return type:
None
- class cloup.constraints.AcceptBetween(min, max)[source]¶
Bases:
WrapperConstraintAbstract class that wraps another constraint and delegates all methods to it. Useful when you want to define a parametric constraint combining other existing constraints minimizing the boilerplate.
This is an alternative to defining a function and using
Rephraser. Feel free to do that in your code, but cloup will stick to the convention that parametric constraints are defined as classes and written in camel-case.Satisfied if the number of set parameters is between
minandmax(included).- Parameters:
min (int) – must be an integer >= 0
max (int) – must be an integer > min
- min_num_params¶
- max_num_params¶
- class cloup.constraints.And(*constraints)[source]¶
Bases:
OperatorIt’s satisfied if all operands are satisfied.
N-ary operator for constraints. :param constraints: operands
- Parameters:
constraints (Constraint)
- HELP_SEP = ' and '¶
Used as separator of all constraints’ help strings.
- check_values(params, ctx)[source]¶
Check that the constraint is satisfied by the input parameters in the given context, which (among other things) contains the values assigned to the parameters in
ctx.params.You probably don’t want to call this method directly. Use
check()instead.- Parameters:
params (Sequence[click.Parameter]) – list of
click.Parameterinstancesctx (click.Context) –
click.Context
- Raises:
- Return type:
None
- __and__(other)[source]¶
- Parameters:
other (Constraint)
- Return type:
- class cloup.constraints.Constraint[source]¶
Bases:
abc.ABCA constraint that can be checked against an arbitrary collection of CLI parameters with respect to a specific
click.Context(which contains the values assigned to the parameters inctx.params).Changed in version 0.9.0: calling a constraint, previously equivalent to
check(), is now equivalent to callingcloup.constrained_params()with this constraint as first argument.- static must_check_consistency(ctx)[source]¶
Return
Trueif consistency checks are enabled.Changed in version 0.9.0: this method now a static method and takes a
click.Contextin input.- Parameters:
ctx (click.Context)
- Return type:
bool
- abstract help(ctx)[source]¶
A description of the constraint.
- Parameters:
ctx (click.Context)
- Return type:
str
- check_consistency(params)[source]¶
Perform some sanity checks that detect inconsistencies between these constraints and the properties of the input parameters (e.g. required).
For example, a constraint that requires the parameters to be mutually exclusive is not consistent with a group of parameters with multiple required options.
These sanity checks are meant to catch developer’s mistakes and don’t depend on the values assigned to the parameters; therefore:
they can be performed before any parameter parsing
they can be disabled in production (setting
check_constraints_consistency=Falseincontext_settings)
- Parameters:
params (Sequence[click.Parameter]) – list of
click.Parameterinstances- Raises:
UnsatisfiableConstraintif the constraint cannot be satisfied independently from the values provided by the user- Return type:
None
- abstract check_values(params, ctx)[source]¶
Check that the constraint is satisfied by the input parameters in the given context, which (among other things) contains the values assigned to the parameters in
ctx.params.You probably don’t want to call this method directly. Use
check()instead.- Parameters:
params (Sequence[click.Parameter]) – list of
click.Parameterinstancesctx (click.Context) –
click.Context
- Raises:
- Return type:
None
- check(params: Sequence[click.Parameter], ctx: click.Context | None = None) None[source]¶
- check(params: Sequence[str], ctx: click.Context | None = None) None
Raise an exception if the constraint is not satisfied by the input parameters in the given (or current) context.
This method calls both
check_consistency()(if enabled) andcheck_values().Tip
By default
check_consistency()is called since it shouldn’t have any performance impact. Nonetheless, you can disable it in production passingcheck_constraints_consistency=Falseas part of yourcontext_settings.- Parameters:
params – an iterable of parameter names or a sequence of
click.Parameterctx – a click.Context; if not provided,
click.get_current_context()is used
- Raises:
- rephrased(help=None, error=None)[source]¶
Override the help string and/or the error message of this constraint wrapping it with a
Rephraser.- Parameters:
help (Union[None, str, HelpRephraser]) – if provided, overrides the help string of this constraint. It can be a string or a function
(ctx: click.Context, constr: Constraint) -> str. If you want to hide this constraint from the help, passhelp="".error (Union[None, str, ErrorRephraser]) –
if provided, overrides the error message of this constraint. It can be:
a string, eventually a
formatstring supporting the replacement fields described inErrorFmt.or a function
(err: ConstraintViolated) -> str; note that aConstraintViolatederror has fields forctx,constraintandparams, so it’s a complete description of what happened.
- Return type:
Hide this constraint from the command help.
- Return type:
- __call__(*param_adders)[source]¶
Equivalent to calling
cloup.constrained_params()with this constraint as first argument.Changed in version 0.9.0: this method, previously equivalent to
check(), is now equivalent to callingcloup.constrained_params()with this constraint as first argument.- Parameters:
param_adders (cloup.typing.Decorator)
- Return type:
Callable[[cloup.typing.F], cloup.typing.F]
- __or__(other)[source]¶
- Parameters:
other (Constraint)
- Return type:
- __and__(other)[source]¶
- Parameters:
other (Constraint)
- Return type:
- class cloup.constraints.ErrorFmt[source]¶
Bases:
cloup._util.FrozenSpaceRephraserallows you to pass aformatstring aserrorargument; this class contains the “replacement fields” supported by such format string. You can use them as following:mutually_exclusive.rephrased( error=f"{ErrorFmt.error}\n" f"Some extra information here." )
- error = '{error}'¶
Replaced by the original error message. Useful if all you want is to append or prepend some extra info to the original error message.
- param_list = '{param_list}'¶
Replaced by a 2-space indented list of the constrained parameters.
- cloup.constraints.ErrorRephraser¶
- cloup.constraints.HelpRephraser¶
- class cloup.constraints.Operator(*constraints)[source]¶
Bases:
Constraint,abc.ABCBase class for all n-ary operators defined on constraints.
N-ary operator for constraints. :param constraints: operands
- Parameters:
constraints (Constraint)
- HELP_SEP: str¶
Used as separator of all constraints’ help strings.
- constraints¶
- help(ctx)[source]¶
A description of the constraint.
- Parameters:
ctx (click.Context)
- Return type:
str
- check_consistency(params)[source]¶
Perform some sanity checks that detect inconsistencies between these constraints and the properties of the input parameters (e.g. required).
For example, a constraint that requires the parameters to be mutually exclusive is not consistent with a group of parameters with multiple required options.
These sanity checks are meant to catch developer’s mistakes and don’t depend on the values assigned to the parameters; therefore:
they can be performed before any parameter parsing
they can be disabled in production (setting
check_constraints_consistency=Falseincontext_settings)
- Parameters:
params (Sequence[click.Parameter]) – list of
click.Parameterinstances- Raises:
UnsatisfiableConstraintif the constraint cannot be satisfied independently from the values provided by the user- Return type:
None
- class cloup.constraints.Or(*constraints)[source]¶
Bases:
OperatorIt’s satisfied if at least one of the operands is satisfied.
N-ary operator for constraints. :param constraints: operands
- Parameters:
constraints (Constraint)
- HELP_SEP = ' or '¶
Used as separator of all constraints’ help strings.
- check_values(params, ctx)[source]¶
Check that the constraint is satisfied by the input parameters in the given context, which (among other things) contains the values assigned to the parameters in
ctx.params.You probably don’t want to call this method directly. Use
check()instead.- Parameters:
params (Sequence[click.Parameter]) – list of
click.Parameterinstancesctx (click.Context) –
click.Context
- Raises:
- Return type:
None
- __or__(other)[source]¶
- Parameters:
other (Constraint)
- Return type:
- class cloup.constraints.Rephraser(constraint, help=None, error=None)[source]¶
Bases:
ConstraintA constraint decorator that can override the help and/or the error message of the wrapped constraint.
You’ll rarely (if ever) use this class directly. In most cases, you’ll use the method
Constraint.rephrased(). Refer to it for more info.See also
Constraint.rephrased()– wraps a constraint with aRephraser.WrapperConstraint– alternative toRephraser.ErrorFmt– describes the keyword you can use in an error format string.
- Parameters:
constraint (Constraint)
help (None | str | Callable[[Context, Constraint], str])
error (None | str | Callable[[ConstraintViolated], str])
- constraint¶
- help(ctx)[source]¶
A description of the constraint.
- Parameters:
ctx (click.Context)
- Return type:
str
- check_consistency(params)[source]¶
Perform some sanity checks that detect inconsistencies between these constraints and the properties of the input parameters (e.g. required).
For example, a constraint that requires the parameters to be mutually exclusive is not consistent with a group of parameters with multiple required options.
These sanity checks are meant to catch developer’s mistakes and don’t depend on the values assigned to the parameters; therefore:
they can be performed before any parameter parsing
they can be disabled in production (setting
check_constraints_consistency=Falseincontext_settings)
- Parameters:
params (Sequence[click.Parameter]) – list of
click.Parameterinstances- Raises:
UnsatisfiableConstraintif the constraint cannot be satisfied independently from the values provided by the user- Return type:
None
- check_values(params, ctx)[source]¶
Check that the constraint is satisfied by the input parameters in the given context, which (among other things) contains the values assigned to the parameters in
ctx.params.You probably don’t want to call this method directly. Use
check()instead.- Parameters:
params (Sequence[click.Parameter]) – list of
click.Parameterinstancesctx (click.Context) –
click.Context
- Raises:
- Return type:
None
- class cloup.constraints.RequireAtLeast(n)[source]¶
Bases:
ConstraintSatisfied if the number of set parameters is >= n.
- Parameters:
n (int)
- min_num_params¶
- help(ctx)[source]¶
A description of the constraint.
- Parameters:
ctx (click.Context)
- Return type:
str
- check_consistency(params)[source]¶
Perform some sanity checks that detect inconsistencies between these constraints and the properties of the input parameters (e.g. required).
For example, a constraint that requires the parameters to be mutually exclusive is not consistent with a group of parameters with multiple required options.
These sanity checks are meant to catch developer’s mistakes and don’t depend on the values assigned to the parameters; therefore:
they can be performed before any parameter parsing
they can be disabled in production (setting
check_constraints_consistency=Falseincontext_settings)
- Parameters:
params (Sequence[click.Parameter]) – list of
click.Parameterinstances- Raises:
UnsatisfiableConstraintif the constraint cannot be satisfied independently from the values provided by the user- Return type:
None
- check_values(params, ctx)[source]¶
Check that the constraint is satisfied by the input parameters in the given context, which (among other things) contains the values assigned to the parameters in
ctx.params.You probably don’t want to call this method directly. Use
check()instead.- Parameters:
params (Sequence[click.Parameter]) – list of
click.Parameterinstancesctx (click.Context) –
click.Context
- Raises:
- Return type:
None
- class cloup.constraints.RequireExactly(n)[source]¶
Bases:
WrapperConstraintRequires an exact number of parameters to be set.
- Parameters:
constraint – the constraint to wrap
attrs – these are just used to generate a
__repr__methodn (int)
- num_params¶
- help(ctx)[source]¶
A description of the constraint.
- Parameters:
ctx (click.Context)
- Return type:
str
- check_values(params, ctx)[source]¶
Check that the constraint is satisfied by the input parameters in the given context, which (among other things) contains the values assigned to the parameters in
ctx.params.You probably don’t want to call this method directly. Use
check()instead.- Parameters:
params (Sequence[click.Parameter]) – list of
click.Parameterinstancesctx (click.Context) –
click.Context
- Raises:
- Return type:
None
- class cloup.constraints.WrapperConstraint(constraint, **attrs)[source]¶
Bases:
ConstraintAbstract class that wraps another constraint and delegates all methods to it. Useful when you want to define a parametric constraint combining other existing constraints minimizing the boilerplate.
This is an alternative to defining a function and using
Rephraser. Feel free to do that in your code, but cloup will stick to the convention that parametric constraints are defined as classes and written in camel-case.- Parameters:
constraint (Constraint) – the constraint to wrap
attrs (Any) – these are just used to generate a
__repr__method
- help(ctx)[source]¶
A description of the constraint.
- Parameters:
ctx (click.Context)
- Return type:
str
- check_consistency(params)[source]¶
Perform some sanity checks that detect inconsistencies between these constraints and the properties of the input parameters (e.g. required).
For example, a constraint that requires the parameters to be mutually exclusive is not consistent with a group of parameters with multiple required options.
These sanity checks are meant to catch developer’s mistakes and don’t depend on the values assigned to the parameters; therefore:
they can be performed before any parameter parsing
they can be disabled in production (setting
check_constraints_consistency=Falseincontext_settings)
- Parameters:
params (Sequence[click.Parameter]) – list of
click.Parameterinstances- Raises:
UnsatisfiableConstraintif the constraint cannot be satisfied independently from the values provided by the user- Return type:
None
- check_values(params, ctx)[source]¶
Check that the constraint is satisfied by the input parameters in the given context, which (among other things) contains the values assigned to the parameters in
ctx.params.You probably don’t want to call this method directly. Use
check()instead.- Parameters:
params (Sequence[click.Parameter]) – list of
click.Parameterinstancesctx (click.Context) –
click.Context
- Raises:
- Return type:
None
- cloup.constraints.accept_none¶
Satisfied if none of the parameters is set. Useful only in conditional constraints.
- cloup.constraints.all_or_none¶
Satisfied if either all or none of the parameters are set.
- cloup.constraints.mutually_exclusive¶
Satisfied if at most one of the parameters is set.
- cloup.constraints.require_all¶
Satisfied if all parameters are set.
- cloup.constraints.require_any¶
Alias for
RequireAtLeast(1).
- cloup.constraints.require_one¶
Alias for
RequireExactly(1).
- class cloup.constraints.BoundConstraintSpec[source]¶
Bases:
NamedTupleA NamedTuple storing a
Constraintand the names of the parameters it has to check.- Parameters:
constraint (Constraint)
param_names (Sequence[str])
- constraint: cloup.constraints._core.Constraint¶
- param_names: Sequence[str]¶
- resolve_params(cmd)[source]¶
- Parameters:
cmd (ConstraintMixin)
- Return type:
BoundConstraint
- class cloup.constraints.ConstraintMixin(*args, constraints=(), show_constraints=None, **kwargs)[source]¶
Provides support for constraints.
- Parameters:
constraints (Sequence[BoundConstraintSpec | BoundConstraint]) – sequence of constraints bound to specific groups of parameters. Note that constraints applied to option groups are collected from the option groups themselves, so they don’t need to be included in this argument.
show_constraints (bool | None) – whether to include a “Constraint” section in the command help. This is also available as a context setting having a lower priority than this attribute.
args (Any) – positional arguments forwarded to the next class in the MRO
kwargs (Any) – keyword arguments forwarded to the next class in the MRO
- show_constraints¶
- optgroup_constraints¶
Constraints applied to
OptionGroupinstances.
- param_constraints: Tuple[BoundConstraint, Ellipsis]¶
Constraints registered using
@constraint(or equivalent method).
- all_constraints¶
All constraints applied to parameter/option groups of this command.
- parse_args(ctx, args)[source]¶
- Parameters:
ctx (click.Context)
args (List[str])
- Return type:
List[str]
- get_params_by_name(names)[source]¶
- Parameters:
names (Iterable[str])
- Return type:
Sequence[click.Parameter]
- format_constraints(ctx, formatter)[source]¶
- Parameters:
ctx (click.Context)
formatter (cloup.HelpFormatter)
- Return type:
None
- cloup.constraints.constrained_params(constr, *param_adders)[source]¶
Return a decorator that adds the given parameters and applies a constraint to them. Equivalent to:
@param_adders[0] ... @param_adders[-1] @constraint(constr, <param names>)
This decorator saves you to manually (re)type the parameter names. It can also be used inside
@option_group.Instead of using this decorator, you can also call the constraint itself:
@constr(*param_adders)
but remember that:
Python 3.9 is the first that allows arbitrary expressions on the right of
@;using a long conditional/composite constraint as decorator may be less readable.
In these cases, you may consider using
@constrained_params.Added in version 0.9.0.
- Parameters:
constr (Constraint) – an instance of
Constraintparam_adders (Callable[[Callable[[...], Any]], Callable[[...], Any]]) – function decorators, each attaching a single parameter to the decorated function.
- Return type:
Callable[[F], F]
- cloup.constraints.constraint(constr, params)[source]¶
Register a constraint on a list of parameters specified by (destination) name (e.g. the default name of
--input-fileisinput_file).- Parameters:
constr (Constraint)
params (Iterable[str])
- Return type:
Callable[[F], F]
- class cloup.constraints.AllSet(*param_names)[source]¶
Bases:
PredicateTrue if all listed parameters are set.
Added in version 0.8.0.
- Parameters:
param_names (str)
- param_names¶
- negated_description(ctx)[source]¶
Succinct description of the negation of this predicate (alias: neg_desc).
- Parameters:
ctx (click.Context)
- Return type:
str
- description(ctx)[source]¶
Succinct description of the predicate (alias: desc).
- Parameters:
ctx (click.Context)
- Return type:
str
- class cloup.constraints.AnySet(*param_names)[source]¶
Bases:
PredicateTrue if any of the listed parameters is set.
Added in version 0.8.0.
- Parameters:
param_names (str)
- param_names¶
- negated_description(ctx)[source]¶
Succinct description of the negation of this predicate (alias: neg_desc).
- Parameters:
ctx (click.Context)
- Return type:
str
- description(ctx)[source]¶
Succinct description of the predicate (alias: desc).
- Parameters:
ctx (click.Context)
- Return type:
str
- class cloup.constraints.Equal(param_name, value)[source]¶
Bases:
PredicateTrue if the parameter value equals
value.- Parameters:
param_name (str)
value (Any)
- param_name¶
- value¶
- description(ctx)[source]¶
Succinct description of the predicate (alias: desc).
- Parameters:
ctx (click.Context)
- Return type:
str
- class cloup.constraints.IsSet(param_name)[source]¶
Bases:
PredicateTrue if the parameter is set.
- Parameters:
param_name (str)
- param_name¶
- description(ctx)[source]¶
Succinct description of the predicate (alias: desc).
- Parameters:
ctx (click.Context)
- Return type:
str
- negated_description(ctx)[source]¶
Succinct description of the negation of this predicate (alias: neg_desc).
- Parameters:
ctx (click.Context)
- Return type:
str
- class cloup.constraints.Not(predicate)[source]¶
Bases:
Predicate,Generic[P]Logical NOT of a predicate.
- Parameters:
predicate (P)
- predicate¶
- description(ctx)[source]¶
Succinct description of the predicate (alias: desc).
- Parameters:
ctx (click.Context)
- Return type:
str
- negated_description(ctx)[source]¶
Succinct description of the negation of this predicate (alias: neg_desc).
- Parameters:
ctx (click.Context)
- Return type:
str
- exception cloup.constraints.ConstraintViolated(message, ctx, constraint, params)[source]¶
Bases:
click.UsageErrorAn internal exception that signals a usage error. This typically aborts any further handling.
- Parameters:
message (str) – the error message to display.
ctx (click.Context) – optionally the context that caused this error. Click will fill in the context automatically in some situations.
constraint (cloup.constraints._core.Constraint)
params (Sequence[click.Parameter])
Initialize self. See help(type(self)) for accurate signature.
- ctx¶
- constraint¶
- params¶
- exception cloup.constraints.UnsatisfiableConstraint(constraint, params, reason)[source]¶
Bases:
ExceptionRaised if a constraint cannot be satisfied by a group of parameters independently from their values at runtime; e.g.
mutually_exclusivecannot be satisfied if multiple of the parameters are required.Initialize self. See help(type(self)) for accurate signature.
- Parameters:
constraint (cloup.constraints._core.Constraint)
params (Iterable[click.Parameter])
reason (str)
- constraint¶
- params¶
- reason¶