:mod:`cloup.constraints` ======================== .. py:module:: cloup.constraints .. autoapi-nested-parse:: Constraints for parameter groups. .. versionadded:: v0.5.0 Submodules ---------- .. toctree:: :titlesonly: :maxdepth: 1 common conditions exceptions Classes ------- .. autosummary:: ~cloup.constraints.If ~cloup.constraints.AcceptAtMost ~cloup.constraints.AcceptBetween ~cloup.constraints.And ~cloup.constraints.Constraint ~cloup.constraints.ErrorFmt ~cloup.constraints.Operator ~cloup.constraints.Or ~cloup.constraints.Rephraser ~cloup.constraints.RequireAtLeast ~cloup.constraints.RequireExactly ~cloup.constraints.WrapperConstraint ~cloup.constraints.BoundConstraintSpec ~cloup.constraints.ConstraintMixin ~cloup.constraints.AllSet ~cloup.constraints.AnySet ~cloup.constraints.Equal ~cloup.constraints.IsSet ~cloup.constraints.Not Functions --------- .. autosummary:: ~cloup.constraints.constrained_params ~cloup.constraints.constraint Attributes ---------- .. autoapisummary:: cloup.constraints.ErrorRephraser cloup.constraints.HelpRephraser cloup.constraints.accept_none cloup.constraints.all_or_none cloup.constraints.mutually_exclusive cloup.constraints.require_all cloup.constraints.require_any cloup.constraints.require_one Contents -------- .. py:class:: If(condition, then, else_ = None) Bases: :py:obj:`cloup.constraints._core.Constraint` Checks one constraint or another depending on the truth value of the condition. .. versionadded:: 0.8.0 you can now pass a sequence of parameter names as condition, which corresponds to the predicate ``AllSet(*param_names)``. :param condition: can be either an instance of ``Predicate`` or (more often) the name of a parameter or a list/tuple of parameters that must be all set for the condition to be true. :param then: a constraint checked if the condition is true. :param else_: an (optional) constraint checked if the condition is false. .. py:method:: help(self, ctx) A description of the constraint. .. py:method:: check_consistency(self, params) 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=False`` in ``context_settings``) :param params: list of :class:`click.Parameter` instances :raises: :exc:`~cloup.constraints.errors.UnsatisfiableConstraint` if the constraint cannot be satisfied independently from the values provided by the user .. py:method:: check_values(self, params, ctx) 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 :meth:`check` instead. :param params: list of :class:`click.Parameter` instances :param ctx: :class:`click.Context` :raises: :exc:`~cloup.constraints.ConstraintViolated` .. py:method:: __repr__(self) Return repr(self). .. py:class:: AcceptAtMost(n) Bases: :py:obj:`Constraint` Satisfied if the number of set parameters is <= n. .. py:method:: help(self, ctx) A description of the constraint. .. py:method:: check_consistency(self, params) 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=False`` in ``context_settings``) :param params: list of :class:`click.Parameter` instances :raises: :exc:`~cloup.constraints.errors.UnsatisfiableConstraint` if the constraint cannot be satisfied independently from the values provided by the user .. py:method:: check_values(self, params, ctx) 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 :meth:`check` instead. :param params: list of :class:`click.Parameter` instances :param ctx: :class:`click.Context` :raises: :exc:`~cloup.constraints.ConstraintViolated` .. py:method:: __repr__(self) Return repr(self). .. py:class:: AcceptBetween(min, max) Bases: :py:obj:`WrapperConstraint` Abstract 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 :class:`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 ``min`` and ``max`` (included). :param min: must be an integer >= 0 :param max: must be an integer > min .. py:method:: help(self, ctx) A description of the constraint. .. py:class:: And(*constraints) Bases: :py:obj:`Operator` It's satisfied if all operands are satisfied. N-ary operator for constraints. :param constraints: operands .. py:attribute:: HELP_SEP :annotation: = and .. py:method:: check_values(self, params, ctx) 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 :meth:`check` instead. :param params: list of :class:`click.Parameter` instances :param ctx: :class:`click.Context` :raises: :exc:`~cloup.constraints.ConstraintViolated` .. py:method:: __and__(self, other) .. py:class:: Constraint Bases: :py:obj:`abc.ABC` A constraint that can be checked against an arbitrary collection of CLI parameters with respect to a specific :class:`click.Context` (which contains the values assigned to the parameters in ``ctx.params``). .. versionchanged:: 0.9.0 calling a constraint, previously equivalent to :meth:`~Constraint.check`, is now equivalent to calling :func:`cloup.constrained_params` with this constraint as first argument. .. py:method:: must_check_consistency(ctx) :staticmethod: Return ``True`` if consistency checks are enabled. .. versionchanged:: 0.9.0 this method now a static method and takes a ``click.Context`` in input. .. py:method:: __getattr__(self, attr) .. py:method:: help(self, ctx) :abstractmethod: A description of the constraint. .. py:method:: check_consistency(self, params) 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=False`` in ``context_settings``) :param params: list of :class:`click.Parameter` instances :raises: :exc:`~cloup.constraints.errors.UnsatisfiableConstraint` if the constraint cannot be satisfied independently from the values provided by the user .. py:method:: check_values(self, params, ctx) :abstractmethod: 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 :meth:`check` instead. :param params: list of :class:`click.Parameter` instances :param ctx: :class:`click.Context` :raises: :exc:`~cloup.constraints.ConstraintViolated` .. py:method:: check(self, params: Sequence[click.Parameter], ctx: Optional[click.Context] = None) -> None check(self, params: Sequence[str], ctx: Optional[click.Context] = 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 :meth:`check_consistency` (if enabled) and :meth:`check_values`. .. tip:: By default :meth:`check_consistency` is called since it shouldn't have any performance impact. Nonetheless, you can disable it in production passing ``check_constraints_consistency=False`` as part of your ``context_settings``. :param params: an iterable of parameter names or a sequence of :class:`click.Parameter` :param ctx: a `click.Context`; if not provided, :func:`click.get_current_context` is used :raises: :exc:`~cloup.constraints.ConstraintViolated` :exc:`~cloup.constraints.UnsatisfiableConstraint` .. py:method:: rephrased(self, help = None, error = None) Override the help string and/or the error message of this constraint wrapping it with a :class:`Rephraser`. :param help: 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, pass ``help=""``. :param error: if provided, overrides the error message of this constraint. It can be: - a string, eventually a ``format`` string supporting the replacement fields described in :class:`ErrorFmt`. - or a function ``(err: ConstraintViolated) -> str``; note that a :class:`ConstraintViolated` error has fields for ``ctx``, ``constraint`` and ``params``, so it's a complete description of what happened. .. py:method:: hidden(self) Hide this constraint from the command help. .. py:method:: __call__(self, *param_adders) Equivalent to calling :func:`cloup.constrained_params` with this constraint as first argument. .. versionchanged:: 0.9.0 this method, previously equivalent to :meth:`~Constraint.check`, is now equivalent to calling :func:`cloup.constrained_params` with this constraint as first argument. .. py:method:: __or__(self, other) .. py:method:: __and__(self, other) .. py:method:: __repr__(self) Return repr(self). .. py:class:: ErrorFmt Bases: :py:obj:`cloup._util.FrozenSpace` :class:`Rephraser` allows you to pass a ``format`` string as ``error`` argument; 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." ) .. py:attribute:: error :annotation: = {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. .. py:attribute:: param_list :annotation: = {param_list} Replaced by a 2-space indented list of the constrained parameters. .. py:data:: ErrorRephraser .. py:data:: HelpRephraser .. py:class:: Operator(*constraints) Bases: :py:obj:`Constraint`, :py:obj:`abc.ABC` Base class for all n-ary operators defined on constraints. N-ary operator for constraints. :param constraints: operands .. py:attribute:: HELP_SEP :annotation: :str Used as separator of all constraints' help strings. .. py:method:: help(self, ctx) A description of the constraint. .. py:method:: check_consistency(self, params) 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=False`` in ``context_settings``) :param params: list of :class:`click.Parameter` instances :raises: :exc:`~cloup.constraints.errors.UnsatisfiableConstraint` if the constraint cannot be satisfied independently from the values provided by the user .. py:method:: __repr__(self) Return repr(self). .. py:class:: Or(*constraints) Bases: :py:obj:`Operator` It's satisfied if at least one of the operands is satisfied. N-ary operator for constraints. :param constraints: operands .. py:attribute:: HELP_SEP :annotation: = or .. py:method:: check_values(self, params, ctx) 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 :meth:`check` instead. :param params: list of :class:`click.Parameter` instances :param ctx: :class:`click.Context` :raises: :exc:`~cloup.constraints.ConstraintViolated` .. py:method:: __or__(self, other) .. py:class:: Rephraser(constraint, help = None, error = None) Bases: :py:obj:`Constraint` A 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 :meth:`Constraint.rephrased`. Refer to it for more info. .. seealso:: - :meth:`Constraint.rephrased` -- wraps a constraint with a ``Rephraser``. - :class:`WrapperConstraint` -- alternative to ``Rephraser``. - :class:`ErrorFmt` -- describes the keyword you can use in an error format string. .. py:method:: help(self, ctx) A description of the constraint. .. py:method:: check_consistency(self, params) 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=False`` in ``context_settings``) :param params: list of :class:`click.Parameter` instances :raises: :exc:`~cloup.constraints.errors.UnsatisfiableConstraint` if the constraint cannot be satisfied independently from the values provided by the user .. py:method:: check_values(self, params, ctx) 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 :meth:`check` instead. :param params: list of :class:`click.Parameter` instances :param ctx: :class:`click.Context` :raises: :exc:`~cloup.constraints.ConstraintViolated` .. py:method:: __repr__(self) Return repr(self). .. py:class:: RequireAtLeast(n) Bases: :py:obj:`Constraint` Satisfied if the number of set parameters is >= n. .. py:method:: help(self, ctx) A description of the constraint. .. py:method:: check_consistency(self, params) 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=False`` in ``context_settings``) :param params: list of :class:`click.Parameter` instances :raises: :exc:`~cloup.constraints.errors.UnsatisfiableConstraint` if the constraint cannot be satisfied independently from the values provided by the user .. py:method:: check_values(self, params, ctx) 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 :meth:`check` instead. :param params: list of :class:`click.Parameter` instances :param ctx: :class:`click.Context` :raises: :exc:`~cloup.constraints.ConstraintViolated` .. py:method:: __repr__(self) Return repr(self). .. py:class:: RequireExactly(n) Bases: :py:obj:`WrapperConstraint` Requires an exact number of parameters to be set. :param constraint: the constraint to wrap :param attrs: these are just used to generate a ``__repr__`` method .. py:method:: help(self, ctx) A description of the constraint. .. py:method:: check_values(self, params, ctx) 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 :meth:`check` instead. :param params: list of :class:`click.Parameter` instances :param ctx: :class:`click.Context` :raises: :exc:`~cloup.constraints.ConstraintViolated` .. py:method:: __repr__(self) Return repr(self). .. py:class:: WrapperConstraint(constraint, **attrs) Bases: :py:obj:`Constraint` Abstract 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 :class:`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. :param constraint: the constraint to wrap :param attrs: these are just used to generate a ``__repr__`` method .. py:method:: help(self, ctx) A description of the constraint. .. py:method:: check_consistency(self, params) 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=False`` in ``context_settings``) :param params: list of :class:`click.Parameter` instances :raises: :exc:`~cloup.constraints.errors.UnsatisfiableConstraint` if the constraint cannot be satisfied independently from the values provided by the user .. py:method:: check_values(self, params, ctx) 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 :meth:`check` instead. :param params: list of :class:`click.Parameter` instances :param ctx: :class:`click.Context` :raises: :exc:`~cloup.constraints.ConstraintViolated` .. py:method:: __repr__(self) Return repr(self). .. py:data:: accept_none Satisfied if none of the parameters is set. Useful only in conditional constraints. .. py:data:: all_or_none Satisfied if either all or none of the parameters are set. .. py:data:: mutually_exclusive Satisfied if at most one of the parameters is set. .. py:data:: require_all Satisfied if all parameters are set. .. py:data:: require_any Alias for ``RequireAtLeast(1)``. .. py:data:: require_one Alias for ``RequireExactly(1)``. .. py:class:: BoundConstraintSpec Bases: :py:obj:`NamedTuple` A NamedTuple storing a ``Constraint`` and the **names of the parameters** it has to check. .. py:attribute:: constraint :annotation: :cloup.constraints._core.Constraint .. py:attribute:: param_names :annotation: :Union[Sequence[str]] .. py:method:: resolve_params(self, cmd) .. py:class:: ConstraintMixin(*args, constraints = (), show_constraints = None, **kwargs) Provides support for constraints. :param constraints: 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. :param show_constraints: 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. :param args: positional arguments forwarded to the next class in the MRO :param kwargs: keyword arguments forwarded to the next class in the MRO .. py:attribute:: optgroup_constraints Constraints applied to ``OptionGroup`` instances. .. py:attribute:: param_constraints :annotation: :Tuple[BoundConstraint, Ellipsis] Constraints registered using ``@constraint`` (or equivalent method). .. py:attribute:: all_constraints All constraints applied to parameter/option groups of this command. .. py:method:: parse_args(self, ctx, args) .. py:method:: get_param_by_name(self, name) .. py:method:: get_params_by_name(self, names) .. py:method:: format_constraints(self, ctx, formatter) .. py:method:: must_show_constraints(self, ctx) .. py:function:: constrained_params(constr, *param_adders) Return a decorator that adds the given parameters and applies a constraint to them. Equivalent to:: @param_adders[0] ... @param_adders[-1] @constraint(constr, ) 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``. .. versionadded:: 0.9.0 :param constr: an instance of :class:`Constraint` :param param_adders: function decorators, each attaching a single parameter to the decorated function. .. py:function:: constraint(constr, params) Register a constraint on a list of parameters specified by (destination) name (e.g. the default name of ``--input-file`` is ``input_file``). .. py:class:: AllSet(*param_names) Bases: :py:obj:`Predicate` True if all listed parameters are set. .. versionadded:: 0.8.0 .. py:method:: negated_description(self, ctx) Succinct description of the negation of this predicate (alias: `neg_desc`). .. py:method:: description(self, ctx) Succinct description of the predicate (alias: `desc`). .. py:method:: __call__(self, ctx) Evaluate the predicate on the given context. .. py:method:: __and__(self, other) .. py:class:: AnySet(*param_names) Bases: :py:obj:`Predicate` True if any of the listed parameters is set. .. versionadded:: 0.8.0 .. py:method:: negated_description(self, ctx) Succinct description of the negation of this predicate (alias: `neg_desc`). .. py:method:: description(self, ctx) Succinct description of the predicate (alias: `desc`). .. py:method:: __call__(self, ctx) Evaluate the predicate on the given context. .. py:method:: __or__(self, other) .. py:class:: Equal(param_name, value) Bases: :py:obj:`Predicate` True if the parameter value equals ``value``. .. py:method:: description(self, ctx) Succinct description of the predicate (alias: `desc`). .. py:method:: negated_description(self, ctx) Succinct description of the negation of this predicate (alias: `neg_desc`). .. py:method:: __call__(self, ctx) Evaluate the predicate on the given context. .. py:class:: IsSet(param_name) Bases: :py:obj:`Predicate` True if the parameter is set. .. py:method:: description(self, ctx) Succinct description of the predicate (alias: `desc`). .. py:method:: negated_description(self, ctx) Succinct description of the negation of this predicate (alias: `neg_desc`). .. py:method:: __call__(self, ctx) Evaluate the predicate on the given context. .. py:method:: __and__(self, other) .. py:method:: __or__(self, other) .. py:class:: Not(predicate) Bases: :py:obj:`Predicate`, :py:obj:`Generic`\ [\ :py:obj:`P`\ ] Logical NOT of a predicate. .. py:method:: description(self, ctx) Succinct description of the predicate (alias: `desc`). .. py:method:: negated_description(self, ctx) Succinct description of the negation of this predicate (alias: `neg_desc`). .. py:method:: __call__(self, ctx) Evaluate the predicate on the given context. .. py:method:: __invert__(self) .. py:method:: __repr__(self) Return repr(self). .. py:exception:: ConstraintViolated(message, ctx, constraint, params) Bases: :py:obj:`click.UsageError` An internal exception that signals a usage error. This typically aborts any further handling. :param message: the error message to display. :param ctx: optionally the context that caused this error. Click will fill in the context automatically in some situations. Initialize self. See help(type(self)) for accurate signature. .. py:method:: default(cls, desc, ctx, constraint, params) :classmethod: .. py:exception:: UnsatisfiableConstraint(constraint, params, reason) Bases: :py:obj:`Exception` Raised if a constraint cannot be satisfied by a group of parameters independently from their values at runtime; e.g. ``mutually_exclusive`` cannot be satisfied if multiple of the parameters are required. Initialize self. See help(type(self)) for accurate signature.