Debian Codegraph @

lib/ansible/module_utils/_internal/_dataclass_validation.py

raw
1 # Copyright (c) 2024 Ansible Project
2 # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
3
4 """Code generation of __post_init__ methods for efficient dataclass field type checking at runtime."""
5
6 from __future__ import annotations
7
8 import atexit
9 import functools
10 import itertools
11 import shutil
12 import tempfile
13 import types
14 import typing as t
15
16 _write_generated_code_to_disk = False
17
18 # deprecated: description='types.UnionType is available in Python 3.10' python_version='3.9'
19 try:
20 _union_type: type | None = types.UnionType # type: ignore[attr-defined]
21 _union_types: tuple = (t.Union, types.UnionType) # type: ignore[attr-defined]
22 except AttributeError:
23 _union_type = None # type: ignore[assignment]
24 _union_types = (t.Union,) # type: ignore[assignment]
25
26
27 def inject_post_init_validation(cls: type, allow_subclasses=False) -> None:
28 """Inject a __post_init__ field validation method on the given dataclass. An existing __post_init__ attribute must already exist."""
29 # DTFIX-FUTURE: when cls must have a __post_init__, enforcing it as a no-op would be nice, but is tricky on slotted dataclasses due to double-creation
30 post_validate_name = '_post_validate'
31 method_name = '__post_init__'
32 exec_globals: dict[str, t.Any] = {}
33 known_types: dict[type, str] = {}
34 lines: list[str] = []
35 field_type_hints = t.get_type_hints(cls)
36 indent = 1
37
38 def append_line(line: str) -> None:
39 """Append a line to the generated source at the current indentation level."""
40 lines.append((' ' * indent * 4) + line)
41
42 def register_type(target_type: type) -> str:
43 """Register the target type and return the local name."""
44 target_name = f'{target_type.__module__.replace(".", "_")}_{target_type.__name__}'
45
46 known_types[target_type] = target_name
47 exec_globals[target_name] = target_type
48
49 return target_name
50
51 def validate_value(target_name: str, target_ref: str, target_type: type) -> None:
52 """Generate code to validate the specified value."""
53 nonlocal indent
54
55 origin_type = t.get_origin(target_type)
56
57 if origin_type is t.ClassVar:
58 return # ignore annotations which are not fields, indicated by the t.ClassVar annotation
59
60 allowed_types = _get_allowed_types(target_type)
61
62 # check value
63
64 if origin_type is t.Literal:
65 # DTFIX-FUTURE: support optional literals
66
67 values = t.get_args(target_type)
68
69 append_line(f"""if {target_ref} not in {values}:""")
70 append_line(f""" raise ValueError(rf"{target_name} must be one of {values} instead of {{{target_ref}!r}}")""")
71
72 allowed_refs = [register_type(allowed_type) for allowed_type in allowed_types]
73 allowed_names = [repr(allowed_type) for allowed_type in allowed_types]
74
75 if allow_subclasses:
76 if len(allowed_refs) == 1:
77 append_line(f"""if not isinstance({target_ref}, {allowed_refs[0]}):""")
78 else:
79 append_line(f"""if not isinstance({target_ref}, ({', '.join(allowed_refs)})):""")
80 else:
81 if len(allowed_refs) == 1:
82 append_line(f"""if type({target_ref}) is not {allowed_refs[0]}:""")
83 else:
84 append_line(f"""if type({target_ref}) not in ({', '.join(allowed_refs)}):""")
85
86 append_line(f""" raise TypeError(f"{target_name} must be {' or '.join(allowed_names)} instead of {{type({target_ref})}}")""")
87
88 # check elements (for containers)
89
90 if target_ref.startswith('self.'):
91 local_ref = target_ref[5:]
92 else:
93 local_ref = target_ref
94
95 if tuple in allowed_types:
96 tuple_type = _extract_type(target_type, tuple)
97
98 idx_ref = f'{local_ref}_idx'
99 item_ref = f'{local_ref}_item'
100 item_name = f'{target_name}[{{{idx_ref}!r}}]'
101 item_type, _ellipsis = t.get_args(tuple_type)
102
103 if _ellipsis is not ...:
104 raise ValueError(f"{cls} tuple fields must be a tuple of a single element type")
105
106 append_line(f"""if isinstance({target_ref}, {known_types[tuple]}):""")
107 append_line(f""" for {idx_ref}, {item_ref} in enumerate({target_ref}):""")
108
109 indent += 2
110 validate_value(target_name=item_name, target_ref=item_ref, target_type=item_type)
111 indent -= 2
112
113 if list in allowed_types:
114 list_type = _extract_type(target_type, list)
115
116 idx_ref = f'{local_ref}_idx'
117 item_ref = f'{local_ref}_item'
118 item_name = f'{target_name}[{{{idx_ref}!r}}]'
119 (item_type,) = t.get_args(list_type)
120
121 append_line(f"""if isinstance({target_ref}, {known_types[list]}):""")
122 append_line(f""" for {idx_ref}, {item_ref} in enumerate({target_ref}):""")
123
124 indent += 2
125 validate_value(target_name=item_name, target_ref=item_ref, target_type=item_type)
126 indent -= 2
127
128 if dict in allowed_types:
129 dict_type = _extract_type(target_type, dict)
130
131 key_ref, value_ref = f'{local_ref}_key', f'{local_ref}_value'
132 key_type, value_type = t.get_args(dict_type)
133 key_name, value_name = f'{target_name!r} key {{{key_ref}!r}}', f'{target_name}[{{{key_ref}!r}}]'
134
135 append_line(f"""if isinstance({target_ref}, {known_types[dict]}):""")
136 append_line(f""" for {key_ref}, {value_ref} in {target_ref}.items():""")
137
138 indent += 2
139 validate_value(target_name=key_name, target_ref=key_ref, target_type=key_type)
140 validate_value(target_name=value_name, target_ref=value_ref, target_type=value_type)
141 indent -= 2
142
143 for field_name in cls.__annotations__:
144 validate_value(target_name=f'{{type(self).__name__}}.{field_name}', target_ref=f'self.{field_name}', target_type=field_type_hints[field_name])
145
146 if hasattr(cls, post_validate_name):
147 append_line(f"self.{post_validate_name}()")
148
149 if not lines:
150 return # nothing to validate (empty dataclass)
151
152 if '__init__' in cls.__dict__ and not hasattr(cls, method_name):
153 raise ValueError(f"{cls} must have a {method_name!r} method to override when invoked after the '__init__' method is created")
154
155 if any(hasattr(parent, method_name) for parent in cls.__mro__[1:]):
156 lines.insert(0, f' super({register_type(cls)}, self).{method_name}()')
157
158 lines.insert(0, f'def {method_name}(self):')
159
160 source = '\n'.join(lines) + '\n'
161
162 if _write_generated_code_to_disk:
163 tmp = tempfile.NamedTemporaryFile(mode='w+t', suffix=f'-{cls.__module__}.{cls.__name__}.py', delete=False, dir=_get_temporary_directory())
164
165 tmp.write(source)
166 tmp.flush()
167
168 filename = tmp.name
169 else:
170 filename = f'<string> generated for {cls}'
171
172 code = compile(source, filename, 'exec')
173
174 exec(code, exec_globals)
175 setattr(cls, method_name, exec_globals[method_name])
176
177
178 @functools.lru_cache(maxsize=1)
179 def _get_temporary_directory() -> str:
180 """Create a temporary directory and return its full path. The directory will be deleted when the process exits."""
181 temp_dir = tempfile.mkdtemp()
182
183 atexit.register(lambda: shutil.rmtree(temp_dir))
184
185 return temp_dir
186
187
188 def _get_allowed_types(target_type: type) -> tuple[type, ...]:
189 """Return a tuple of types usable in instance checks for the given target_type."""
190 origin_type = t.get_origin(target_type)
191
192 if origin_type in _union_types:
193 allowed_types = tuple(set(itertools.chain.from_iterable(_get_allowed_types(arg) for arg in t.get_args(target_type))))
194 elif origin_type is t.Literal:
195 allowed_types = (str,) # DTFIX-FUTURE: support non-str literal types
196 elif origin_type:
197 allowed_types = (origin_type,)
198 else:
199 allowed_types = (target_type,)
200
201 return allowed_types
202
203
204 def _extract_type(target_type: type, of_type: type) -> type:
205 """Return `of_type` from `target_type`, where `target_type` may be a union."""
206 origin_type = t.get_origin(target_type)
207
208 if origin_type is of_type: # pylint: disable=unidiomatic-typecheck
209 return target_type
210
211 if origin_type is t.Union or (_union_type and isinstance(target_type, _union_type)):
212 args = t.get_args(target_type)
213 extracted_types = [arg for arg in args if type(arg) is of_type or t.get_origin(arg) is of_type] # pylint: disable=unidiomatic-typecheck
214 (extracted_type,) = extracted_types
215 return extracted_type
216
217 raise NotImplementedError(f'{target_type} is not supported')