Debian Codegraph @

cloup/constraints/_conditional.py

raw
1 """
2 This modules contains classes for creating conditional constraints.
3 """
4 from typing import Optional, Sequence, Union
5
6 from click import Context, Parameter
7
8 from ._core import Constraint
9 from .conditions import AllSet, IsSet, Predicate
10 from .exceptions import ConstraintViolated
11 from .._util import make_repr
12
13
14 def as_predicate(arg: Union[str, Sequence[str], Predicate]) -> Predicate:
15 if isinstance(arg, str):
16 return IsSet(arg)
17 elif isinstance(arg, Predicate):
18 return arg
19 elif isinstance(arg, Sequence):
20 return AllSet(*arg)
21 else:
22 raise TypeError("`arg` should be a string, a list of strings or a `Predicate`")
23
24
25 class If(Constraint):
26 """
27 Checks one constraint or another depending on the truth value of the condition.
28
29 .. versionadded:: 0.8.0
30 you can now pass a sequence of parameter names as condition, which
31 corresponds to the predicate ``AllSet(*param_names)``.
32
33 :param condition:
34 can be either an instance of ``Predicate`` or (more often) the name of a
35 parameter or a list/tuple of parameters that must be all set for the
36 condition to be true.
37 :param then:
38 a constraint checked if the condition is true.
39 :param else_:
40 an (optional) constraint checked if the condition is false.
41 """
42
43 def __init__(
44 self,
45 condition: Union[str, Sequence[str], Predicate],
46 then: Constraint,
47 else_: Optional[Constraint] = None,
48 ):
49 self._condition = as_predicate(condition)
50 self._then = then
51 self._else = else_
52
53 def help(self, ctx: Context) -> str:
54 condition = self._condition.description(ctx)
55 then_help = self._then.help(ctx)
56 else_help = self._else.help(ctx) if self._else else None
57 if not self._else:
58 return f"{then_help} if {condition}"
59 else:
60 return f"{then_help} if {condition}, otherwise {else_help}"
61
62 def check_consistency(self, params: Sequence[Parameter]) -> None:
63 self._then.check_consistency(params)
64 if self._else:
65 self._else.check_consistency(params)
66
67 def check_values(self, params: Sequence[Parameter], ctx: Context) -> None:
68 condition = self._condition
69 condition_is_true = condition(ctx)
70 branch = self._then if condition_is_true else self._else
71 if branch is None:
72 return
73 try:
74 branch.check_values(params, ctx=ctx)
75 except ConstraintViolated as err:
76 desc = (
77 condition.description(ctx)
78 if condition_is_true
79 else condition.negated_description(ctx)
80 )
81 raise ConstraintViolated(
82 f"when {desc}, {err}", ctx=ctx, constraint=self, params=params
83 )
84
85 def __repr__(self) -> str:
86 if self._else:
87 return make_repr(self, self._condition, then=self._then, else_=self._else)
88 return make_repr(self, self._condition, then=self._then)