Coverage for typer / _coercion.py: 100%
161 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-11-18 11:12 +0000
« prev ^ index » next coverage.py v7.13.1, created at 2026-11-18 11:12 +0000
1import os 1adefbghcij
2from abc import ABC, abstractmethod 1adefbghcij
3from collections.abc import Callable 1adefbghcij
4from dataclasses import dataclass 1adefbghcij
5from datetime import datetime 1adefbghcij
6from typing import TYPE_CHECKING, Any 1adefbghcij
8from ._click import Context 1adefbghcij
9from ._click.exceptions import BadParameter, UsageError 1adefbghcij
10from ._display import get_error_msg 1adefbghcij
11from ._param_types import ( 1adefbghcij
12 ParameterAnnotation,
13 _open_cli_file,
14 annotation_from_prompt,
15 choice_coercion_annotation,
16 file_coercion_annotation,
17 is_file_annotation,
18 lenient_issubclass,
19 path_type_name,
20 resolve_file_mode,
21 routes_to_path,
22 validate_annotation_structure,
23)
24from ._typing import get_args, get_origin, is_number_type 1adefbghcij
25from .models import OptionInfo, ParameterInfo 1adefbghcij
27if TYPE_CHECKING: 1adefbghcij
28 from pydantic import TypeAdapter
30 from .core import _TyperParameter
33@dataclass(frozen=True) 1adefbghcij
34class TypeDescriptor: 1adefbghcij
35 annotation: ParameterAnnotation 1abc
36 parameter_info: ParameterInfo 1abc
37 file_annotation: Any | None 1abc
39 @property 1adefbghcij
40 def is_list(self) -> bool: 1adefbghcij
41 return lenient_issubclass(get_origin(self.annotation), list) 1adefbghcij
43 @property 1adefbghcij
44 def is_tuple(self) -> bool: 1adefbghcij
45 return lenient_issubclass(get_origin(self.annotation), tuple) 1adefbghcij
47 @property 1adefbghcij
48 def is_datetime(self) -> bool: 1adefbghcij
49 return self.annotation is datetime 1adefbghcij
51 @property 1adefbghcij
52 def is_ranged(self) -> bool: 1adefbghcij
53 has_min_or_max = ( 1adefbghcij
54 self.parameter_info.min is not None or self.parameter_info.max is not None
55 )
56 return is_number_type(self.annotation) and has_min_or_max 1adefbghcij
58 @property 1adefbghcij
59 def is_path(self) -> bool: 1adefbghcij
60 return routes_to_path(self.annotation, self.parameter_info) 1adefbghcij
62 @property 1adefbghcij
63 def is_choice(self) -> bool: 1adefbghcij
64 return self.choices is not None 1adefbghcij
66 @property 1adefbghcij
67 def is_file(self) -> bool: 1adefbghcij
68 return self.file_annotation is not None 1adefbghcij
70 @property 1adefbghcij
71 def path_type(self) -> str: 1adefbghcij
72 return path_type_name(self.parameter_info) 1adefbghcij
74 @property 1adefbghcij
75 def choices(self) -> tuple[Any, ...] | None: 1adefbghcij
76 if self.is_list: 1adefbghcij
77 args = get_args(self.annotation) 1adefbghcij
78 if len(args) == 1: 1adefbghcij
79 choice = choice_coercion_annotation(args[0], self.parameter_info) 1adefbghcij
80 if choice is not None: 1adefbghcij
81 return choice[0] 1adefbghcij
82 choice = choice_coercion_annotation(self.annotation, self.parameter_info) 1adefbghcij
83 if choice is not None: 1adefbghcij
84 return choice[0] 1adefbghcij
85 return None 1adefbghcij
87 @property 1adefbghcij
88 def case_sensitive(self) -> bool: 1adefbghcij
89 return self.parameter_info.case_sensitive 1adefbghcij
91 @property 1adefbghcij
92 def ranged_type_name(self) -> str: 1adefbghcij
93 assert isinstance(self.annotation, type) 1adefbghcij
94 return self.annotation.__name__ 1adefbghcij
96 @property 1adefbghcij
97 def tuple_arity(self) -> int | None: 1adefbghcij
98 if not self.is_tuple: 1adefbghcij
99 return None 1adefbghcij
100 return len(get_args(self.annotation)) 1adefbghcij
102 @property 1adefbghcij
103 def envvar_list_splitter(self) -> str | None: 1adefbghcij
104 if self.is_file or self.is_path: 1adefbghcij
105 return os.path.pathsep 1adefbghcij
106 if self.is_list: 1adefbghcij
107 args = get_args(self.annotation) 1adefbghcij
108 if len(args) == 1 and ( 1adefbghcij
109 is_file_annotation(args[0])
110 or routes_to_path(args[0], self.parameter_info)
111 ):
112 return os.path.pathsep 1adefbghcij
113 return None 1adefbghcij
116def resolve_type_descriptor( 1adefbghcij
117 annotation: ParameterAnnotation,
118 parameter_info: ParameterInfo,
119) -> TypeDescriptor:
120 """Create type descriptor for one parameter annotation."""
121 validate_annotation_structure(annotation) 1adefbghcij
122 file_annotation = file_coercion_annotation(annotation) 1adefbghcij
123 return TypeDescriptor( 1adefbghcij
124 annotation=annotation,
125 parameter_info=parameter_info,
126 file_annotation=file_annotation,
127 )
130@dataclass(frozen=True) 1adefbghcij
131class RuntimeParam(ABC): 1adefbghcij
132 """Runtime coercion contract for one command parameter."""
134 parameter_info: ParameterInfo 1abc
135 annotation: ParameterAnnotation 1abc
137 def coerce(self, value: Any, param: "_TyperParameter", ctx: Context) -> Any: 1adefbghcij
138 is_multi_value = param.multiple or param.nargs == -1 1adefbghcij
139 if value is None: 1adefbghcij
140 if is_multi_value: 1adefbghcij
141 return () 1adefbghcij
142 return None 1adefbghcij
143 if is_multi_value and isinstance(value, str): 1adefbghcij
144 raise BadParameter("Value must be an iterable.", ctx=ctx, param=param) 1adefbghcij
145 return self._coerce_value(value, param=param, ctx=ctx) 1adefbghcij
147 @abstractmethod 1adefbghcij
148 def _coerce_value(self, value: Any, param: "_TyperParameter", ctx: Context) -> Any: 1adefbghcij
149 pass # pragma: no cover
152@dataclass(frozen=True) 1adefbghcij
153class AdapterRuntimeParam(RuntimeParam): 1adefbghcij
154 """Coercion via a Pydantic TypeAdapter."""
156 adapter: "TypeAdapter[Any]" 1abc
158 def _coerce_value(self, value: Any, param: "_TyperParameter", ctx: Context) -> Any: 1adefbghcij
159 from pydantic import ValidationError 1adefbghcij
161 from ._adapters import validation_context 1adefbghcij
163 try: 1adefbghcij
164 return self.adapter.validate_python( 1adefbghcij
165 value,
166 context=validation_context(ctx, param),
167 )
168 except ValidationError as exc: 1adefbghcij
169 raise BadParameter(get_error_msg(exc), ctx=ctx, param=param) from exc 1adefbghcij
172@dataclass(frozen=True) 1adefbghcij
173class FileRuntimeParam(RuntimeParam): 1adefbghcij
174 """Coercion by opening CLI file paths into IO streams."""
176 file_annotation: Any 1abc
178 def _coerce_value(self, value: Any, param: "_TyperParameter", ctx: Context) -> Any: 1adefbghcij
179 def coerce_non_file(item: Any, annotation: Any) -> Any: 1adefbghcij
180 # Ensure non-file annotations (e.g. in mixed tuples) are also dealt with
181 type_desc = resolve_type_descriptor(annotation, self.parameter_info) 1adefbghcij
182 return build_runtime_param(type_desc)._coerce_value( 1adefbghcij
183 item, param=param, ctx=ctx
184 )
186 def open_file(item: Any, annotation: Any) -> Any: 1adefbghcij
187 mode = resolve_file_mode(self.parameter_info, annotation) 1adefbghcij
188 return _open_cli_file( 1adefbghcij
189 item, self.parameter_info, mode=mode, param=param, ctx=ctx
190 )
192 if isinstance(value, (list, tuple)): 1adefbghcij
193 # tuple may be heterogeneous,
194 # lists should have a single type which will be duplicated
195 annotations: Any = ( 1adefbghcij
196 self.file_annotation
197 if isinstance(self.file_annotation, tuple)
198 else (self.file_annotation,) * len(value)
199 )
200 pairs = list(zip(value, annotations, strict=True)) 1adefbghcij
201 # Validate non-file elements before opening files, so a bad
202 # sibling value does not leave an unclosed file handle.
203 coerced = [ 1adefbghcij
204 item if is_file_annotation(ann) else coerce_non_file(item, ann)
205 for item, ann in pairs
206 ]
207 zipped = zip(coerced, annotations, strict=True) 1adefbghcij
208 return type(value)( 1adefbghcij
209 open_file(item, ann) if is_file_annotation(ann) else item
210 for item, ann in zipped
211 )
213 assert is_file_annotation(self.file_annotation) 1adefbghcij
214 return open_file(value, self.file_annotation) 1adefbghcij
217@dataclass(frozen=True) 1adefbghcij
218class PassThroughRuntimeParam(RuntimeParam): 1adefbghcij
219 """Coercion for annotations that cannot use a Pydantic TypeAdapter."""
221 def _coerce_value(self, value: Any, param: "_TyperParameter", ctx: Context) -> Any: 1adefbghcij
222 annotation = self.annotation 1adefbghcij
223 if isinstance(annotation, type): 1adefbghcij
224 if isinstance(value, annotation): 1adefbghcij
225 return value 1adefbghcij
226 label = getattr(annotation, "__name__", repr(annotation)) 1adefbghcij
227 raise BadParameter( 1adefbghcij
228 f"Value {value!r} is not a valid {label}.",
229 ctx=ctx,
230 param=param,
231 )
234def build_runtime_param(descriptor: TypeDescriptor) -> RuntimeParam: 1adefbghcij
235 """Build runtime coercion from a resolved type descriptor."""
236 from . import _adapters 1adefbghcij
238 args = { 1adefbghcij
239 "annotation": descriptor.annotation,
240 "parameter_info": descriptor.parameter_info,
241 }
242 if descriptor.file_annotation is not None: 1adefbghcij
243 return FileRuntimeParam(**args, file_annotation=descriptor.file_annotation) 1adefbghcij
244 adapter = _adapters.try_build_adapter(**args) 1adefbghcij
245 if adapter is not None: 1adefbghcij
246 return AdapterRuntimeParam(**args, adapter=adapter) 1adefbghcij
247 return PassThroughRuntimeParam(**args) 1adefbghcij
250def bool_flag_type_descriptor() -> TypeDescriptor: 1adefbghcij
251 """Resolved type for a standalone boolean flag option."""
252 return resolve_type_descriptor( 1adefbghcij
253 annotation=bool,
254 parameter_info=OptionInfo(),
255 )
258def prompt_value_proc( 1adefbghcij
259 param_type: Any | None = None,
260 default: Any | None = None,
261) -> Callable[[Any], Any]:
262 """Coerce interactive prompt input via the runtime adapter layer."""
263 from pydantic import ValidationError 1adefbghcij
265 from . import _adapters 1adefbghcij
267 annotation = annotation_from_prompt(param_type, default) 1adefbghcij
269 parameter_info = OptionInfo() 1adefbghcij
270 adapter = _adapters.try_build_adapter(annotation, parameter_info) 1adefbghcij
272 if adapter is not None: 1adefbghcij
274 def coerce(value: Any) -> Any: 1adefbghcij
275 try: 1adefbghcij
276 return adapter.validate_python(value) 1adefbghcij
277 except ValidationError as exc: 1adefbghcij
278 raise UsageError(get_error_msg(exc)) from exc 1adefbghcij
280 return coerce 1adefbghcij
282 def coerce_pass_through(value: Any) -> Any: 1adefbghcij
283 assert isinstance(annotation, type) 1adefbghcij
284 if isinstance(value, annotation): 1adefbghcij
285 return value 1adefbghcij
286 raise UsageError(f"Value {value!r} is not a valid {annotation.__name__}.") 1adefbghcij
288 return coerce_pass_through 1adefbghcij