generated from BrianPugh/python-template
-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
parameter.py
248 lines (194 loc) · 7.84 KB
/
parameter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import inspect
from functools import partial
from typing import (
Any,
Callable,
Iterable,
Optional,
Tuple,
Type,
Union,
cast,
get_args,
get_origin,
)
import attrs
from attrs import field, frozen
import cyclopts.utils
from cyclopts._convert import (
AnnotatedType,
convert,
get_origin_and_validate,
resolve,
resolve_optional,
)
from cyclopts.group import Group
from cyclopts.utils import (
default_name_transform,
optional_to_tuple_converter,
record_init,
to_tuple_converter,
)
def _double_hyphen_validator(instance, attribute, values):
if not values:
return
for value in values:
if value is not None and not value.startswith("--"):
raise ValueError(f'{attribute.alias} value must start with "--".')
def _negative_converter(default: Tuple[str, ...]):
def converter(value) -> Tuple[str, ...]:
if value is None:
return default
else:
return to_tuple_converter(value)
return converter
@record_init("_provided_args")
@frozen
class Parameter:
"""Cyclopts configuration for individual function parameters."""
# All documentation has been moved to ``docs/api.rst`` for greater control with attrs.
# This can ONLY ever be a Tuple[str, ...]
name: Union[None, str, Iterable[str]] = field(
default=None,
converter=lambda x: cast(Tuple[str, ...], to_tuple_converter(x)),
)
_converter: Callable = field(default=None, alias="converter")
# This can ONLY ever be a Tuple[Callable, ...]
validator: Union[None, Callable, Iterable[Callable]] = field(
default=(),
converter=lambda x: cast(Tuple[Callable, ...], to_tuple_converter(x)),
)
# This can ONLY ever be a Tuple[str, ...]
negative: Union[None, str, Iterable[str]] = field(default=None, converter=optional_to_tuple_converter)
# This can ONLY ever be a Tuple[Union[Group, str], ...]
group: Union[None, Group, str, Iterable[Union[Group, str]]] = field(
default=None, converter=to_tuple_converter, hash=False
)
parse: bool = field(default=None, converter=attrs.converters.default_if_none(True))
_show: Optional[bool] = field(default=None, alias="show")
show_default: Optional[bool] = field(default=None)
show_choices: bool = field(default=None, converter=attrs.converters.default_if_none(True))
help: Optional[str] = field(default=None)
show_env_var: bool = field(default=None, converter=attrs.converters.default_if_none(True))
# This can ONLY ever be a Tuple[str, ...]
env_var: Union[None, str, Iterable[str]] = field(
default=None,
converter=lambda x: cast(Tuple[str, ...], to_tuple_converter(x)),
)
negative_bool: Tuple[str, ...] = field(
default=None,
converter=_negative_converter(("--no-",)),
validator=_double_hyphen_validator,
)
negative_iterable: Tuple[str, ...] = field(
default=None,
converter=_negative_converter(("--empty-",)),
validator=_double_hyphen_validator,
)
required: Optional[bool] = field(default=None)
allow_leading_hyphen: bool = field(default=False)
name_transform: Optional[Callable[[str], str]] = field(
default=None,
converter=attrs.converters.default_if_none(default_name_transform),
kw_only=True,
)
# Populated by the record_attrs_init_args decorator.
_provided_args: Tuple[str] = field(default=(), init=False, eq=False)
@property
def show(self):
return self._show if self._show is not None else self.parse
@property
def converter(self):
return self._converter if self._converter else partial(convert, name_transform=self.name_transform)
def get_negatives(self, type_, *names: str) -> Tuple[str, ...]:
type_ = get_origin(type_) or type_
if self.negative is not None:
return self.negative # pyright: ignore
elif type_ not in (bool, list, set):
return ()
out = []
for name in names:
if name.startswith("--"):
name = name[2:]
elif name.startswith("-"):
# Do not support automatic negation for short flags.
continue
else:
raise ValueError("All parameters should have started with '-' or '--'.")
negative_prefixes = self.negative_bool if type_ is bool else self.negative_iterable
for negative_prefix in negative_prefixes:
out.append(f"{negative_prefix}{name}")
return tuple(out)
def __repr__(self):
"""Only shows non-default values."""
content = ", ".join(
[
f"{a.alias}={getattr(self, a.name)!r}"
for a in self.__attrs_attrs__ # pyright: ignore[reportAttributeAccessIssue]
if a.alias in self._provided_args
]
)
return f"{type(self).__name__}({content})"
@classmethod
def combine(cls, *parameters: Optional["Parameter"]) -> "Parameter":
"""Returns a new Parameter with values of ``parameters``.
Parameters
----------
`*parameters`: Optional[Parameter]
Parameters who's attributes override ``self`` attributes.
Ordered from least-to-highest attribute priority.
"""
kwargs = {}
for parameter in parameters:
if parameter is None:
continue
for a in parameter.__attrs_attrs__: # pyright: ignore[reportAttributeAccessIssue]
if a.init and a.alias in parameter._provided_args:
kwargs[a.alias] = getattr(parameter, a.name)
return cls(**kwargs)
@classmethod
def default(cls) -> "Parameter":
"""Create a Parameter with all Cyclopts-default values.
This is different than just :class:`Parameter` because the default
values will be recorded and override all upstream parameter values.
"""
return cls(
**{a.alias: a.default for a in cls.__attrs_attrs__ if a.init} # pyright: ignore[reportAttributeAccessIssue]
)
def validate_command(f: Callable):
"""Validate if a function abides by Cyclopts's rules.
Raises
------
ValueError
Function has naming or parameter/signature inconsistencies.
"""
signature = cyclopts.utils.signature(f)
for iparam in signature.parameters.values():
get_origin_and_validate(iparam.annotation)
type_, cparam = get_hint_parameter(iparam)
if not cparam.parse and iparam.kind is not iparam.KEYWORD_ONLY:
raise ValueError("Parameter.parse=False must be used with a KEYWORD_ONLY function parameter.")
def get_hint_parameter(type_: Any, *default_parameters: Optional[Parameter]) -> Tuple[Type, Parameter]:
"""Get the type hint and Cyclopts :class:`Parameter` from a type-hint.
If a ``cyclopts.Parameter`` is not found, a default Parameter is returned.
"""
cyclopts_parameters = []
if isinstance(type_, inspect.Parameter):
annotation = type_.annotation
if annotation is inspect.Parameter.empty or resolve(annotation) is Any:
if type_.default in (inspect.Parameter.empty, None):
annotation = str
else:
return get_hint_parameter(type(type_.default), *default_parameters)
else:
annotation = type_
if annotation is inspect.Parameter.empty:
annotation = str
annotation = resolve_optional(annotation)
if type(annotation) is AnnotatedType:
annotations = annotation.__metadata__ # pyright: ignore[reportGeneralTypeIssues]
annotation = get_args(annotation)[0]
cyclopts_parameters = [x for x in annotations if isinstance(x, Parameter)]
annotation = resolve(annotation)
cparam = Parameter.combine(*default_parameters, *cyclopts_parameters)
return annotation, cparam