Debian Codegraph @

lib/ansible/_internal/_templating/_lazy_containers.py

raw
1 from __future__ import annotations
2
3 import copy
4 import dataclasses
5 import functools
6 import types
7 import typing as t
8
9 from jinja2.environment import TemplateModule
10
11 from ansible.module_utils._internal._datatag import (
12 AnsibleTagHelper,
13 AnsibleTaggedObject,
14 _AnsibleTaggedDict,
15 _AnsibleTaggedList,
16 _AnsibleTaggedTuple,
17 _NO_INSTANCE_STORAGE,
18 _try_get_internal_tags_mapping,
19 )
20
21 from ansible.utils.sentinel import Sentinel
22 from ansible.errors import AnsibleVariableTypeError
23 from ansible._internal._errors._handler import Skippable
24 from ansible.vars.hostvars import HostVarsVars, HostVars
25
26 from ._access import AnsibleAccessContext
27 from ._jinja_common import Marker, _TemplateConfig
28 from ._utils import TemplateContext, PASS_THROUGH_SCALAR_VAR_TYPES, LazyOptions
29
30 if t.TYPE_CHECKING:
31 from ._engine import TemplateEngine
32
33 _KNOWN_TYPES: t.Final[set[type]] = (
34 {
35 HostVars, # example: hostvars
36 HostVarsVars, # example: hostvars.localhost | select
37 type, # example: range(20) | list # triggered on retrieval of `range` type from globals
38 range, # example: range(20) | list # triggered when returning a `range` instance from a call
39 types.FunctionType, # example: undef() | default("blah")
40 types.MethodType, # example: ansible_facts.get | type_debug
41 functools.partial,
42 type(''.startswith), # example: inventory_hostname.upper | type_debug # using `startswith` to resolve `builtin_function_or_method`
43 TemplateModule, # example: '{% import "importme.j2" as im %}{{ im | type_debug }}'
44 }
45 | set(PASS_THROUGH_SCALAR_VAR_TYPES)
46 | set(Marker._concrete_subclasses)
47 )
48 """
49 These types are known to the templating system.
50 In addition to the statically defined types, additional types will be added at runtime.
51 When enabled in config, this set will be used to determine if an encountered type should trigger a warning or error.
52 """
53
54
55 def register_known_types(*args: type) -> None:
56 """Register a type with the template engine so it will not trigger warnings or errors when encountered."""
57 _KNOWN_TYPES.update(args)
58
59
60 class UnsupportedConstructionMethodError(RuntimeError):
61 """Error raised when attempting to construct a lazy container with unsupported arguments."""
62
63 def __init__(self):
64 super().__init__("Direct construction of lazy containers is not supported.")
65
66
67 @t.final
68 @dataclasses.dataclass(frozen=True, slots=True)
69 class _LazyValue:
70 """Wrapper around values to indicate lazy behavior has not yet been applied."""
71
72 value: t.Any
73
74
75 @t.final
76 @dataclasses.dataclass(frozen=True, kw_only=True, slots=True)
77 class _LazyValueSource:
78 """Intermediate value source for lazy-eligible collection copy operations."""
79
80 source: t.Iterable
81 templar: TemplateEngine
82 lazy_options: LazyOptions
83
84
85 @t.final
86 class _NoKeySentinel(Sentinel):
87 """Sentinel used to indicate a requested key was not found."""
88
89
90 # There are several operations performed by lazy containers, with some variation between types.
91 #
92 # Columns: D=dict, L=list, T=tuple
93 # Cells: l=lazy (upon access), n=non-lazy (__init__/__new__)
94 #
95 # D L T Feature Description
96 # - - - ----------- ---------------------------------------------------------------
97 # l l n propagation when container items which are containers become lazy instances
98 # l l n transform when transforms are applied to container items
99 # l l n templating when templating is performed on container items
100 # l l l access when access calls are performed on container items
101
102
103 class _AnsibleLazyTemplateMixin:
104 __slots__ = _NO_INSTANCE_STORAGE
105
106 _dispatch_types: t.ClassVar[dict[type, type[_AnsibleLazyTemplateMixin]]] = {} # populated by __init_subclass__
107 _container_types: t.ClassVar[set[type]] = set() # populated by __init_subclass__
108
109 _native_type: t.ClassVar[type] # from AnsibleTaggedObject
110
111 _SLOTS: t.Final = (
112 '_templar',
113 '_lazy_options',
114 )
115
116 _templar: TemplateEngine
117 _lazy_options: LazyOptions
118
119 def __init_subclass__(cls, **kwargs) -> None:
120 tagged_type = cls.__mro__[1]
121 native_type = tagged_type.__mro__[1]
122
123 for check_type in (tagged_type, native_type):
124 if conflicting_type := cls._dispatch_types.get(check_type):
125 raise TypeError(f"Lazy mixin {cls.__name__!r} type {check_type.__name__!r} conflicts with {conflicting_type.__name__!r}.")
126
127 cls._dispatch_types[native_type] = cls
128 cls._dispatch_types[tagged_type] = cls
129 cls._container_types.add(native_type)
130 cls._empty_tags_as_native = False # never revert to the native type when no tags remain
131
132 register_known_types(cls)
133
134 def __init__(self, contents: t.Iterable | _LazyValueSource) -> None:
135 if isinstance(contents, _LazyValueSource):
136 self._templar = contents.templar
137 self._lazy_options = contents.lazy_options
138 elif isinstance(contents, _AnsibleLazyTemplateMixin):
139 self._templar = contents._templar
140 self._lazy_options = contents._lazy_options
141 else:
142 raise UnsupportedConstructionMethodError()
143
144 def __reduce_ex__(self, protocol):
145 raise NotImplementedError("Pickling of Ansible lazy objects is not permitted.")
146
147 @staticmethod
148 def _try_create(item: t.Any, lazy_options: LazyOptions = LazyOptions.DEFAULT) -> t.Any:
149 """
150 If `item` is a container type which supports lazy access and/or templating, return a lazy wrapped version -- otherwise return it as-is.
151 When returning as-is, a warning or error may be generated for unknown types.
152 The `lazy_options.skip_templates` argument should be set to `True` when `item` is sourced from a plugin instead of Ansible variable storage.
153 This provides backwards compatibility and reduces lazy overhead, as plugins do not normally introduce templates.
154 If a plugin needs to introduce templates, the plugin is responsible for invoking the templar and returning the result.
155 """
156 item_type = type(item)
157
158 # Try to use exact type match first to determine which wrapper (if any) to apply; isinstance checks
159 # are extremely expensive, so try to avoid them for our commonly-supported types.
160 if (dispatcher := _AnsibleLazyTemplateMixin._dispatch_types.get(item_type)) is not None:
161 # Create a generator that yields the elements of `item` wrapped in a `_LazyValue` wrapper.
162 # The wrapper is used to signal to the lazy container that the value must be processed before being returned.
163 # Values added to the lazy container later through other means will be returned as-is, without any special processing.
164 lazy_values = dispatcher._lazy_values(item, lazy_options)
165 tags_mapping = _try_get_internal_tags_mapping(item)
166 value = t.cast(AnsibleTaggedObject, dispatcher)._instance_factory(lazy_values, tags_mapping)
167
168 return value
169
170 with Skippable, _TemplateConfig.unknown_type_encountered_handler.handle(AnsibleVariableTypeError, skip_on_ignore=True):
171 if item_type not in _KNOWN_TYPES:
172 raise AnsibleVariableTypeError(
173 message=f"Encountered unknown type {item_type.__name__!r} during template operation.",
174 help_text="Use supported types to avoid unexpected behavior.",
175 obj=TemplateContext.current().template_value,
176 )
177
178 return item
179
180 def _is_not_lazy_combine_candidate(self, other: object) -> bool:
181 """Returns `True` if `other` cannot be lazily combined with the current instance due to differing templar/options, otherwise returns `False`."""
182 return isinstance(other, _AnsibleLazyTemplateMixin) and (self._templar is not other._templar or self._lazy_options != other._lazy_options)
183
184 def _non_lazy_copy(self) -> t.Collection:
185 """
186 Return a non-lazy copy of this collection.
187 Any remaining lazy wrapped values will be unwrapped without further processing.
188 Tags on this instance will be preserved on the returned copy.
189 """
190 raise NotImplementedError() # pragma: nocover
191
192 @staticmethod
193 def _lazy_values(values: t.Any, lazy_options: LazyOptions) -> _LazyValueSource:
194 """
195 Return an iterable that wraps each of the given elements in a lazy wrapper.
196 Only elements wrapped this way will receive lazy processing when retrieved from the collection.
197 """
198 # DTFIX-FUTURE: check relative performance of method-local vs stored generator expressions on implementations of this method
199 raise NotImplementedError() # pragma: nocover
200
201 def _proxy_or_render_lazy_value(self, key: t.Any, value: t.Any) -> t.Any:
202 """
203 Ensure that the value is lazy-proxied or rendered, and if a key is provided, replace the original value with the result.
204 """
205 if type(value) is not _LazyValue: # pylint: disable=unidiomatic-typecheck
206 if self._lazy_options.access:
207 AnsibleAccessContext.current().access(value)
208
209 return value
210
211 original_value = value.value
212
213 if self._lazy_options.access:
214 AnsibleAccessContext.current().access(original_value)
215
216 new_value = self._templar.template(original_value, lazy_options=self._lazy_options)
217
218 if new_value is not original_value and self._lazy_options.access:
219 AnsibleAccessContext.current().access(new_value)
220
221 if key is not _NoKeySentinel:
222 self._native_type.__setitem__(self, key, new_value) # type: ignore # pylint: disable=unnecessary-dunder-call
223
224 return new_value
225
226
227 @t.final # consumers of lazy collections rely heavily on the concrete types being final
228 class _AnsibleLazyTemplateDict(_AnsibleTaggedDict, _AnsibleLazyTemplateMixin):
229 __slots__ = _AnsibleLazyTemplateMixin._SLOTS
230
231 def __init__(self, contents: t.Iterable | _LazyValueSource, /, **kwargs) -> None:
232 if isinstance(contents, _AnsibleLazyTemplateDict):
233 super().__init__(dict.items(contents), **kwargs)
234 elif isinstance(contents, _LazyValueSource):
235 super().__init__(contents.source, **kwargs)
236 else:
237 raise UnsupportedConstructionMethodError()
238
239 _AnsibleLazyTemplateMixin.__init__(self, contents)
240
241 def get(self, key: t.Any, default: t.Any = None) -> t.Any:
242 if (value := super().get(key, _NoKeySentinel)) is _NoKeySentinel:
243 return default
244
245 return self._proxy_or_render_lazy_value(key, value)
246
247 def __getitem__(self, key: t.Any, /) -> t.Any:
248 return self._proxy_or_render_lazy_value(key, super().__getitem__(key))
249
250 def __str__(self):
251 return str(self.copy()._native_copy()) # inefficient, but avoids mutating the current instance (to make debugging practical)
252
253 def __repr__(self):
254 return repr(self.copy()._native_copy()) # inefficient, but avoids mutating the current instance (to make debugging practical)
255
256 def __iter__(self):
257 # We're using the base implementation, but must override `__iter__` to skip `dict` fast-path copy, which would bypass lazy behavior.
258 # See: https://github.com/python/cpython/blob/ffcc450a9b8b6927549b501eff7ac14abc238448/Objects/dictobject.c#L3861-L3864
259 return super().__iter__()
260
261 def setdefault(self, key, default=None, /) -> t.Any:
262 if (value := self.get(key, _NoKeySentinel)) is not _NoKeySentinel:
263 return value
264
265 super().__setitem__(key, default)
266
267 return default
268
269 def items(self):
270 for key, value in super().items():
271 yield key, self._proxy_or_render_lazy_value(key, value)
272
273 def values(self):
274 for _key, value in self.items():
275 yield value
276
277 def pop(self, key, default=_NoKeySentinel, /) -> t.Any:
278 if (value := super().get(key, _NoKeySentinel)) is _NoKeySentinel:
279 if default is _NoKeySentinel:
280 raise KeyError(key)
281
282 return default
283
284 value = self._proxy_or_render_lazy_value(_NoKeySentinel, value)
285
286 del self[key]
287
288 return value
289
290 def popitem(self) -> t.Any:
291 try:
292 key = next(reversed(self))
293 except StopIteration:
294 raise KeyError("popitem(): dictionary is empty")
295
296 value = self._proxy_or_render_lazy_value(_NoKeySentinel, self[key])
297
298 del self[key]
299
300 return key, value
301
302 def _native_copy(self) -> dict:
303 return dict(self.items())
304
305 @staticmethod
306 def _item_source(value: dict) -> dict | _LazyValueSource:
307 if isinstance(value, _AnsibleLazyTemplateDict):
308 return _LazyValueSource(source=dict.items(value), templar=value._templar, lazy_options=value._lazy_options)
309
310 return value
311
312 def _yield_non_lazy_dict_items(self) -> t.Iterator[tuple[str, t.Any]]:
313 """
314 Delegate to the base collection items iterator to yield the raw contents.
315 As of Python 3.13, generator functions are significantly faster than inline generator expressions.
316 """
317 for k, v in dict.items(self):
318 yield k, v.value if type(v) is _LazyValue else v # pylint: disable=unidiomatic-typecheck
319
320 def _non_lazy_copy(self) -> dict:
321 return AnsibleTagHelper.tag_copy(self, self._yield_non_lazy_dict_items(), value_type=dict)
322
323 @staticmethod
324 def _lazy_values(values: dict, lazy_options: LazyOptions) -> _LazyValueSource:
325 return _LazyValueSource(source=((k, _LazyValue(v)) for k, v in values.items()), templar=TemplateContext.current().templar, lazy_options=lazy_options)
326
327 @staticmethod
328 def _proxy_or_render_other(other: t.Any | None) -> None:
329 """Call `_proxy_or_render_lazy_values` if `other` is a lazy dict. Used internally by comparison methods."""
330 if type(other) is _AnsibleLazyTemplateDict: # pylint: disable=unidiomatic-typecheck
331 other._proxy_or_render_lazy_values()
332
333 def _proxy_or_render_lazy_values(self) -> None:
334 """Ensure all `_LazyValue` wrapped values have been processed."""
335 for _unused in self.values():
336 pass
337
338 def __eq__(self, other):
339 self._proxy_or_render_lazy_values()
340 self._proxy_or_render_other(other)
341 return super().__eq__(other)
342
343 def __ne__(self, other):
344 self._proxy_or_render_lazy_values()
345 self._proxy_or_render_other(other)
346 return super().__ne__(other)
347
348 def __or__(self, other):
349 # DTFIX-FUTURE: support preservation of laziness when possible like we do for list
350 # Both sides end up going through _proxy_or_render_lazy_value, so there's no Templar preservation needed.
351 # In the future this could be made more lazy when both Templar instances are the same, or if per-value Templar tracking was used.
352 return super().__or__(other)
353
354 def __ror__(self, other):
355 # DTFIX-FUTURE: support preservation of laziness when possible like we do for list
356 # Both sides end up going through _proxy_or_render_lazy_value, so there's no Templar preservation needed.
357 # In the future this could be made more lazy when both Templar instances are the same, or if per-value Templar tracking was used.
358 return super().__ror__(other)
359
360 def __deepcopy__(self, memo):
361 return _AnsibleLazyTemplateDict(
362 _LazyValueSource(
363 source=((copy.deepcopy(k), copy.deepcopy(v)) for k, v in super().items()),
364 templar=copy.deepcopy(self._templar),
365 lazy_options=copy.deepcopy(self._lazy_options),
366 )
367 )
368
369
370 @t.final # consumers of lazy collections rely heavily on the concrete types being final
371 class _AnsibleLazyTemplateList(_AnsibleTaggedList, _AnsibleLazyTemplateMixin):
372 __slots__ = _AnsibleLazyTemplateMixin._SLOTS
373
374 def __init__(self, contents: t.Iterable | _LazyValueSource, /) -> None:
375 if isinstance(contents, _AnsibleLazyTemplateList):
376 super().__init__(list.__iter__(contents))
377 elif isinstance(contents, _LazyValueSource):
378 super().__init__(contents.source)
379 else:
380 raise UnsupportedConstructionMethodError()
381
382 _AnsibleLazyTemplateMixin.__init__(self, contents)
383
384 def __getitem__(self, key: t.SupportsIndex | slice, /) -> t.Any:
385 if type(key) is slice: # pylint: disable=unidiomatic-typecheck
386 return _AnsibleLazyTemplateList(_LazyValueSource(source=super().__getitem__(key), templar=self._templar, lazy_options=self._lazy_options))
387
388 return self._proxy_or_render_lazy_value(key, super().__getitem__(key))
389
390 def __iter__(self):
391 for key, value in enumerate(super().__iter__()):
392 yield self._proxy_or_render_lazy_value(key, value)
393
394 def pop(self, idx: t.SupportsIndex = -1, /) -> t.Any:
395 if not self:
396 raise IndexError('pop from empty list')
397
398 try:
399 value = self[idx]
400 except IndexError:
401 raise IndexError('pop index out of range')
402
403 value = self._proxy_or_render_lazy_value(_NoKeySentinel, value)
404
405 del self[idx]
406
407 return value
408
409 def __str__(self):
410 return str(self.copy()._native_copy()) # inefficient, but avoids mutating the current instance (to make debugging practical)
411
412 def __repr__(self):
413 return repr(self.copy()._native_copy()) # inefficient, but avoids mutating the current instance (to make debugging practical)
414
415 @staticmethod
416 def _item_source(value: list) -> list | _LazyValueSource:
417 if isinstance(value, _AnsibleLazyTemplateList):
418 return _LazyValueSource(source=list.__iter__(value), templar=value._templar, lazy_options=value._lazy_options)
419
420 return value
421
422 def _yield_non_lazy_list_items(self):
423 """
424 Delegate to the base collection iterator to yield the raw contents.
425 As of Python 3.13, generator functions are significantly faster than inline generator expressions.
426 """
427 for v in list.__iter__(self):
428 yield v.value if type(v) is _LazyValue else v # pylint: disable=unidiomatic-typecheck
429
430 def _non_lazy_copy(self) -> list:
431 return AnsibleTagHelper.tag_copy(self, self._yield_non_lazy_list_items(), value_type=list)
432
433 @staticmethod
434 def _lazy_values(values: list, lazy_options: LazyOptions) -> _LazyValueSource:
435 return _LazyValueSource(source=(_LazyValue(v) for v in values), templar=TemplateContext.current().templar, lazy_options=lazy_options)
436
437 @staticmethod
438 def _proxy_or_render_other(other: t.Any | None) -> None:
439 """Call `_proxy_or_render_lazy_values` if `other` is a lazy list. Used internally by comparison methods."""
440 if type(other) is _AnsibleLazyTemplateList: # pylint: disable=unidiomatic-typecheck
441 other._proxy_or_render_lazy_values()
442
443 def _proxy_or_render_lazy_values(self) -> None:
444 """Ensure all `_LazyValue` wrapped values have been processed."""
445 for _unused in self:
446 pass
447
448 def __eq__(self, other):
449 self._proxy_or_render_lazy_values()
450 self._proxy_or_render_other(other)
451 return super().__eq__(other)
452
453 def __ne__(self, other):
454 self._proxy_or_render_lazy_values()
455 self._proxy_or_render_other(other)
456 return super().__ne__(other)
457
458 def __gt__(self, other):
459 self._proxy_or_render_lazy_values()
460 self._proxy_or_render_other(other)
461 return super().__gt__(other)
462
463 def __ge__(self, other):
464 self._proxy_or_render_lazy_values()
465 self._proxy_or_render_other(other)
466 return super().__ge__(other)
467
468 def __lt__(self, other):
469 self._proxy_or_render_lazy_values()
470 self._proxy_or_render_other(other)
471 return super().__lt__(other)
472
473 def __le__(self, other):
474 self._proxy_or_render_lazy_values()
475 self._proxy_or_render_other(other)
476 return super().__le__(other)
477
478 def __contains__(self, item):
479 self._proxy_or_render_lazy_values()
480 return super().__contains__(item)
481
482 def __reversed__(self):
483 for idx in range(self.__len__() - 1, -1, -1):
484 yield self[idx]
485
486 def __add__(self, other):
487 if self._is_not_lazy_combine_candidate(other):
488 # When other is lazy with a different templar/options, it cannot be lazily combined with self and a plain list must be returned.
489 # If other is a list, de-lazify both, otherwise just let the operation fail.
490
491 if isinstance(other, _AnsibleLazyTemplateList):
492 self._proxy_or_render_lazy_values()
493 other._proxy_or_render_lazy_values()
494
495 return super().__add__(other)
496
497 # For all other cases, the new list inherits our templar and all values stay lazy.
498 # We use list.__add__ to avoid implementing all its error behavior.
499 return _AnsibleLazyTemplateList(_LazyValueSource(source=super().__add__(other), templar=self._templar, lazy_options=self._lazy_options))
500
501 def __radd__(self, other):
502 if not (other_add := getattr(other, '__add__', None)):
503 raise TypeError(f'unsupported operand type(s) for +: {type(other).__name__!r} and {type(self).__name__!r}') from None
504
505 return _AnsibleLazyTemplateList(_LazyValueSource(source=other_add(self), templar=self._templar, lazy_options=self._lazy_options))
506
507 def __mul__(self, other):
508 return _AnsibleLazyTemplateList(_LazyValueSource(source=super().__mul__(other), templar=self._templar, lazy_options=self._lazy_options))
509
510 def __rmul__(self, other):
511 return _AnsibleLazyTemplateList(_LazyValueSource(source=super().__rmul__(other), templar=self._templar, lazy_options=self._lazy_options))
512
513 def index(self, *args, **kwargs) -> int:
514 self._proxy_or_render_lazy_values()
515 return super().index(*args, **kwargs)
516
517 def remove(self, *args, **kwargs) -> None:
518 self._proxy_or_render_lazy_values()
519 super().remove(*args, **kwargs)
520
521 def sort(self, *args, **kwargs) -> None:
522 self._proxy_or_render_lazy_values()
523 super().sort(*args, **kwargs)
524
525 def __deepcopy__(self, memo):
526 return _AnsibleLazyTemplateList(
527 _LazyValueSource(
528 source=(copy.deepcopy(v) for v in super().__iter__()),
529 templar=copy.deepcopy(self._templar),
530 lazy_options=copy.deepcopy(self._lazy_options),
531 )
532 )
533
534
535 @t.final # consumers of lazy collections rely heavily on the concrete types being final
536 class _AnsibleLazyAccessTuple(_AnsibleTaggedTuple, _AnsibleLazyTemplateMixin):
537 """
538 A tagged tuple subclass that provides only managed access for existing lazy values.
539
540 Since tuples are immutable, they cannot support lazy templating (which would change the tuple's value as templates were resolved).
541 When this type is created, each value in the source tuple is lazified:
542
543 * template strings are templated immediately (possibly resulting in lazy containers)
544 * non-tuple containers are lazy-wrapped
545 * tuples are immediately recursively lazy-wrapped
546 * transformations are applied immediately
547
548 The resulting object provides only managed access to its values (e.g., deprecation warnings, tripwires), and propagates to new lazy containers
549 created as a results of managed access.
550 """
551
552 # DTFIX5: ensure we have tests that explicitly verify this behavior
553
554 # nonempty __slots__ not supported for subtype of 'tuple'
555
556 def __new__(cls, contents: t.Iterable | _LazyValueSource, /) -> t.Self:
557 if isinstance(contents, _AnsibleLazyAccessTuple):
558 return super().__new__(cls, tuple.__iter__(contents))
559
560 if isinstance(contents, _LazyValueSource):
561 return super().__new__(cls, contents.source)
562
563 raise UnsupportedConstructionMethodError()
564
565 def __init__(self, contents: t.Iterable | _LazyValueSource, /) -> None:
566 _AnsibleLazyTemplateMixin.__init__(self, contents)
567
568 def __getitem__(self, key: t.SupportsIndex | slice, /) -> t.Any:
569 if type(key) is slice: # pylint: disable=unidiomatic-typecheck
570 return _AnsibleLazyAccessTuple(_LazyValueSource(source=super().__getitem__(key), templar=self._templar, lazy_options=self._lazy_options))
571
572 value = super().__getitem__(key)
573
574 if self._lazy_options.access:
575 AnsibleAccessContext.current().access(value)
576
577 return value
578
579 @staticmethod
580 def _item_source(value: tuple) -> tuple | _LazyValueSource:
581 if isinstance(value, _AnsibleLazyAccessTuple):
582 return _LazyValueSource(source=tuple.__iter__(value), templar=value._templar, lazy_options=value._lazy_options)
583
584 return value
585
586 @staticmethod
587 def _lazy_values(values: t.Any, lazy_options: LazyOptions) -> _LazyValueSource:
588 templar = TemplateContext.current().templar
589
590 return _LazyValueSource(source=(templar.template(value, lazy_options=lazy_options) for value in values), templar=templar, lazy_options=lazy_options)
591
592 def _non_lazy_copy(self) -> tuple:
593 return AnsibleTagHelper.tag_copy(self, self, value_type=tuple)
594
595 def __deepcopy__(self, memo):
596 return _AnsibleLazyAccessTuple(
597 _LazyValueSource(
598 source=(copy.deepcopy(v) for v in super().__iter__()),
599 templar=copy.deepcopy(self._templar),
600 lazy_options=copy.deepcopy(self._lazy_options),
601 )
602 )
603
604
605 def lazify_container(value: t.Any) -> t.Any:
606 """
607 If the given value is a supported container type, return its lazy version, otherwise return the value as-is.
608 This is used to ensure that managed access and templating occur on args and kwargs to a callable, even if they were sourced from Jinja constants.
609
610 Since both variable access and plugin output are already lazified, this mostly affects Jinja constant containers.
611 However, plugins that directly invoke other plugins (e.g., `Environment.call_filter`) are another potential source of non-lazy containers.
612 In these cases, templating will occur for trusted templates automatically upon access.
613
614 Sets, tuples, and dictionary keys cannot be lazy, since their correct operation requires hashability and equality.
615 These properties are mutually exclusive with the following lazy features:
616
617 - managed access on encrypted strings - may raise errors on both operations when decryption fails
618 - managed access on markers - must raise errors on both operations
619 - templating - mutates values
620
621 That leaves non-raising managed access as the only remaining feature, which is insufficient to warrant lazy support.
622 """
623 return _AnsibleLazyTemplateMixin._try_create(value)
624
625
626 def lazify_container_args(item: tuple) -> tuple:
627 """Return the given args with values converted to lazy containers as needed."""
628 return tuple(lazify_container(value) for value in item)
629
630
631 def lazify_container_kwargs(item: dict[str, t.Any]) -> dict[str, t.Any]:
632 """Return the given kwargs with values converted to lazy containers as needed."""
633 return {key: lazify_container(value) for key, value in item.items()}