Elffuss BraidHub

kikocis/llama-stack public

main · 32.1 KiBRawPermalink
1# Copyright (c) Meta Platforms, Inc. and affiliates.
2# All rights reserved.
3#
4# This source code is licensed under the terms described in the LICENSE file in
5# the root directory of this source tree.
6
7"""
8Type-safe data interchange for Python data classes.
9
10:see: https://github.com/hunyadi/strong_typing
11"""
12
13import dataclasses
14import datetime
15import enum
16import importlib
17import importlib.machinery
18import importlib.util
19import inspect
20import re
21import sys
22import types
23import typing
24import uuid
25from typing import (
26 Any,
27 Callable,
28 Dict,
29 Iterable,
30 List,
31 Literal,
32 NamedTuple,
33 Optional,
34 Protocol,
35 runtime_checkable,
36 Set,
37 Tuple,
38 Type,
39 TypeVar,
40 Union,
41)
42
43if sys.version_info >= (3, 9):
44 from typing import Annotated
45else:
46 from typing_extensions import Annotated
47
48if sys.version_info >= (3, 10):
49 from typing import TypeGuard
50else:
51 from typing_extensions import TypeGuard
52
53S = TypeVar("S")
54T = TypeVar("T")
55K = TypeVar("K")
56V = TypeVar("V")
57
58
59def _is_type_like(data_type: object) -> bool:
60 """
61 Checks if the object is a type or type-like object (e.g. generic type).
62
63 :param data_type: The object to validate.
64 :returns: True if the object is a type or type-like object.
65 """
66
67 if isinstance(data_type, type):
68 # a standard type
69 return True
70 elif typing.get_origin(data_type) is not None:
71 # a generic type such as `list`, `dict` or `set`
72 return True
73 elif hasattr(data_type, "__forward_arg__"):
74 # an instance of `ForwardRef`
75 return True
76 elif data_type is Any:
77 # the special form `Any`
78 return True
79 else:
80 return False
81
82
83if sys.version_info >= (3, 9):
84 TypeLike = Union[type, types.GenericAlias, typing.ForwardRef, Any]
85
86 def is_type_like(
87 data_type: object,
88 ) -> TypeGuard[TypeLike]:
89 """
90 Checks if the object is a type or type-like object (e.g. generic type).
91
92 :param data_type: The object to validate.
93 :returns: True if the object is a type or type-like object.
94 """
95
96 return _is_type_like(data_type)
97
98else:
99 TypeLike = object
100
101 def is_type_like(
102 data_type: object,
103 ) -> bool:
104 return _is_type_like(data_type)
105
106
107def evaluate_member_type(typ: Any, cls: type) -> Any:
108 """
109 Evaluates a forward reference type in a dataclass member.
110
111 :param typ: The dataclass member type to convert.
112 :param cls: The dataclass in which the member is defined.
113 :returns: The evaluated type.
114 """
115
116 return evaluate_type(typ, sys.modules[cls.__module__])
117
118
119def evaluate_type(typ: Any, module: types.ModuleType) -> Any:
120 """
121 Evaluates a forward reference type.
122
123 :param typ: The type to convert, typically a dataclass member type.
124 :param module: The context for the type, i.e. the module in which the member is defined.
125 :returns: The evaluated type.
126 """
127
128 if isinstance(typ, str):
129 # evaluate data-class field whose type annotation is a string
130 return eval(typ, module.__dict__, locals())
131 if isinstance(typ, typing.ForwardRef):
132 if sys.version_info >= (3, 9):
133 return typ._evaluate(module.__dict__, locals(), recursive_guard=frozenset())
134 else:
135 return typ._evaluate(module.__dict__, locals())
136 else:
137 return typ
138
139
140@runtime_checkable
141class DataclassInstance(Protocol):
142 __dataclass_fields__: typing.ClassVar[Dict[str, dataclasses.Field]]
143
144
145def is_dataclass_type(typ: Any) -> TypeGuard[Type[DataclassInstance]]:
146 "True if the argument corresponds to a data class type (but not an instance)."
147
148 typ = unwrap_annotated_type(typ)
149 return isinstance(typ, type) and dataclasses.is_dataclass(typ)
150
151
152def is_dataclass_instance(obj: Any) -> TypeGuard[DataclassInstance]:
153 "True if the argument corresponds to a data class instance (but not a type)."
154
155 return not isinstance(obj, type) and dataclasses.is_dataclass(obj)
156
157
158@dataclasses.dataclass
159class DataclassField:
160 name: str
161 type: Any
162 default: Any
163
164 def __init__(
165 self, name: str, type: Any, default: Any = dataclasses.MISSING
166 ) -> None:
167 self.name = name
168 self.type = type
169 self.default = default
170
171
172def dataclass_fields(cls: Type[DataclassInstance]) -> Iterable[DataclassField]:
173 "Generates the fields of a data-class resolving forward references."
174
175 for field in dataclasses.fields(cls):
176 yield DataclassField(
177 field.name, evaluate_member_type(field.type, cls), field.default
178 )
179
180
181def dataclass_field_by_name(cls: Type[DataclassInstance], name: str) -> DataclassField:
182 "Looks up a field in a data-class by its field name."
183
184 for field in dataclasses.fields(cls):
185 if field.name == name:
186 return DataclassField(field.name, evaluate_member_type(field.type, cls))
187
188 raise LookupError(f"field `{name}` missing from class `{cls.__name__}`")
189
190
191def is_named_tuple_instance(obj: Any) -> TypeGuard[NamedTuple]:
192 "True if the argument corresponds to a named tuple instance."
193
194 return is_named_tuple_type(type(obj))
195
196
197def is_named_tuple_type(typ: Any) -> TypeGuard[Type[NamedTuple]]:
198 """
199 True if the argument corresponds to a named tuple type.
200
201 Calling the function `collections.namedtuple` gives a new type that is a subclass of `tuple` (and no other classes)
202 with a member named `_fields` that is a tuple whose items are all strings.
203 """
204
205 if not isinstance(typ, type):
206 return False
207
208 typ = unwrap_annotated_type(typ)
209
210 b = getattr(typ, "__bases__", None)
211 if b is None:
212 return False
213
214 if len(b) != 1 or b[0] != tuple:
215 return False
216
217 f = getattr(typ, "_fields", None)
218 if not isinstance(f, tuple):
219 return False
220
221 return all(isinstance(n, str) for n in f)
222
223
224if sys.version_info >= (3, 11):
225
226 def is_type_enum(typ: object) -> TypeGuard[Type[enum.Enum]]:
227 "True if the specified type is an enumeration type."
228
229 typ = unwrap_annotated_type(typ)
230 return isinstance(typ, enum.EnumType)
231
232else:
233
234 def is_type_enum(typ: object) -> TypeGuard[Type[enum.Enum]]:
235 "True if the specified type is an enumeration type."
236
237 typ = unwrap_annotated_type(typ)
238
239 # use an explicit isinstance(..., type) check to filter out special forms like generics
240 return isinstance(typ, type) and issubclass(typ, enum.Enum)
241
242
243def enum_value_types(enum_type: Type[enum.Enum]) -> List[type]:
244 """
245 Returns all unique value types of the `enum.Enum` type in definition order.
246 """
247
248 # filter unique enumeration value types by keeping definition order
249 return list(dict.fromkeys(type(e.value) for e in enum_type))
250
251
252def extend_enum(
253 source: Type[enum.Enum],
254) -> Callable[[Type[enum.Enum]], Type[enum.Enum]]:
255 """
256 Creates a new enumeration type extending the set of values in an existing type.
257
258 :param source: The existing enumeration type to be extended with new values.
259 :returns: A new enumeration type with the extended set of values.
260 """
261
262 def wrap(extend: Type[enum.Enum]) -> Type[enum.Enum]:
263 # create new enumeration type combining the values from both types
264 values: Dict[str, Any] = {}
265 values.update((e.name, e.value) for e in source)
266 values.update((e.name, e.value) for e in extend)
267 enum_class: Type[enum.Enum] = enum.Enum(extend.__name__, values) # type: ignore
268
269 # assign the newly created type to the same module where the extending class is defined
270 setattr(enum_class, "__module__", extend.__module__)
271 setattr(enum_class, "__doc__", extend.__doc__)
272 setattr(sys.modules[extend.__module__], extend.__name__, enum_class)
273
274 return enum.unique(enum_class)
275
276 return wrap
277
278
279if sys.version_info >= (3, 10):
280
281 def _is_union_like(typ: object) -> bool:
282 "True if type is a union such as `Union[T1, T2, ...]` or a union type `T1 | T2`."
283
284 return typing.get_origin(typ) is Union or isinstance(typ, types.UnionType)
285
286else:
287
288 def _is_union_like(typ: object) -> bool:
289 "True if type is a union such as `Union[T1, T2, ...]` or a union type `T1 | T2`."
290
291 return typing.get_origin(typ) is Union
292
293
294def is_type_optional(
295 typ: object, strict: bool = False
296) -> TypeGuard[Type[Optional[Any]]]:
297 """
298 True if the type annotation corresponds to an optional type (e.g. `Optional[T]` or `Union[T1,T2,None]`).
299
300 `Optional[T]` is represented as `Union[T, None]` is classic style, and is equivalent to `T | None` in new style.
301
302 :param strict: True if only `Optional[T]` qualifies as an optional type but `Union[T1, T2, None]` does not.
303 """
304
305 typ = unwrap_annotated_type(typ)
306
307 if _is_union_like(typ):
308 args = typing.get_args(typ)
309 if strict and len(args) != 2:
310 return False
311
312 return type(None) in args
313
314 return False
315
316
317def unwrap_optional_type(typ: Type[Optional[T]]) -> Type[T]:
318 """
319 Extracts the inner type of an optional type.
320
321 :param typ: The optional type `Optional[T]`.
322 :returns: The inner type `T`.
323 """
324
325 return rewrap_annotated_type(_unwrap_optional_type, typ)
326
327
328def _unwrap_optional_type(typ: Type[Optional[T]]) -> Type[T]:
329 "Extracts the type qualified as optional (e.g. returns `T` for `Optional[T]`)."
330
331 # Optional[T] is represented internally as Union[T, None]
332 if not _is_union_like(typ):
333 raise TypeError("optional type must have un-subscripted type of Union")
334
335 # will automatically unwrap Union[T] into T
336 return Union[
337 tuple(filter(lambda item: item is not type(None), typing.get_args(typ))) # type: ignore
338 ]
339
340
341def is_type_union(typ: object) -> bool:
342 "True if the type annotation corresponds to a union type (e.g. `Union[T1,T2,T3]`)."
343
344 typ = unwrap_annotated_type(typ)
345
346 if _is_union_like(typ):
347 args = typing.get_args(typ)
348 return len(args) > 2 or type(None) not in args
349
350 return False
351
352
353def unwrap_union_types(typ: object) -> Tuple[object, ...]:
354 """
355 Extracts the inner types of a union type.
356
357 :param typ: The union type `Union[T1, T2, ...]`.
358 :returns: The inner types `T1`, `T2`, etc.
359 """
360
361 return _unwrap_union_types(typ)
362
363
364def _unwrap_union_types(typ: object) -> Tuple[object, ...]:
365 "Extracts the types in a union (e.g. returns a tuple of types `T1` and `T2` for `Union[T1, T2]`)."
366
367 if not _is_union_like(typ):
368 raise TypeError("union type must have un-subscripted type of Union")
369
370 return typing.get_args(typ)
371
372
373def is_type_literal(typ: object) -> bool:
374 "True if the specified type is a literal of one or more constant values, e.g. `Literal['string']` or `Literal[42]`."
375
376 typ = unwrap_annotated_type(typ)
377 return typing.get_origin(typ) is Literal
378
379
380def unwrap_literal_value(typ: object) -> Any:
381 """
382 Extracts the single constant value captured by a literal type.
383
384 :param typ: The literal type `Literal[value]`.
385 :returns: The values captured by the literal type.
386 """
387
388 args = unwrap_literal_values(typ)
389 if len(args) != 1:
390 raise TypeError("too many values in literal type")
391
392 return args[0]
393
394
395def unwrap_literal_values(typ: object) -> Tuple[Any, ...]:
396 """
397 Extracts the constant values captured by a literal type.
398
399 :param typ: The literal type `Literal[value, ...]`.
400 :returns: A tuple of values captured by the literal type.
401 """
402
403 typ = unwrap_annotated_type(typ)
404 return typing.get_args(typ)
405
406
407def unwrap_literal_types(typ: object) -> Tuple[type, ...]:
408 """
409 Extracts the types of the constant values captured by a literal type.
410
411 :param typ: The literal type `Literal[value, ...]`.
412 :returns: A tuple of item types `T` such that `type(value) == T`.
413 """
414
415 return tuple(type(t) for t in unwrap_literal_values(typ))
416
417
418def is_generic_list(typ: object) -> TypeGuard[Type[list]]:
419 "True if the specified type is a generic list, i.e. `List[T]`."
420
421 typ = unwrap_annotated_type(typ)
422 return typing.get_origin(typ) is list
423
424
425def unwrap_generic_list(typ: Type[List[T]]) -> Type[T]:
426 """
427 Extracts the item type of a list type.
428
429 :param typ: The list type `List[T]`.
430 :returns: The item type `T`.
431 """
432
433 return rewrap_annotated_type(_unwrap_generic_list, typ)
434
435
436def _unwrap_generic_list(typ: Type[List[T]]) -> Type[T]:
437 "Extracts the item type of a list type (e.g. returns `T` for `List[T]`)."
438
439 (list_type,) = typing.get_args(typ) # unpack single tuple element
440 return list_type
441
442
443def is_generic_set(typ: object) -> TypeGuard[Type[set]]:
444 "True if the specified type is a generic set, i.e. `Set[T]`."
445
446 typ = unwrap_annotated_type(typ)
447 return typing.get_origin(typ) is set
448
449
450def unwrap_generic_set(typ: Type[Set[T]]) -> Type[T]:
451 """
452 Extracts the item type of a set type.
453
454 :param typ: The set type `Set[T]`.
455 :returns: The item type `T`.
456 """
457
458 return rewrap_annotated_type(_unwrap_generic_set, typ)
459
460
461def _unwrap_generic_set(typ: Type[Set[T]]) -> Type[T]:
462 "Extracts the item type of a set type (e.g. returns `T` for `Set[T]`)."
463
464 (set_type,) = typing.get_args(typ) # unpack single tuple element
465 return set_type
466
467
468def is_generic_dict(typ: object) -> TypeGuard[Type[dict]]:
469 "True if the specified type is a generic dictionary, i.e. `Dict[KeyType, ValueType]`."
470
471 typ = unwrap_annotated_type(typ)
472 return typing.get_origin(typ) is dict
473
474
475def unwrap_generic_dict(typ: Type[Dict[K, V]]) -> Tuple[Type[K], Type[V]]:
476 """
477 Extracts the key and value types of a dictionary type as a tuple.
478
479 :param typ: The dictionary type `Dict[K, V]`.
480 :returns: The key and value types `K` and `V`.
481 """
482
483 return _unwrap_generic_dict(unwrap_annotated_type(typ))
484
485
486def _unwrap_generic_dict(typ: Type[Dict[K, V]]) -> Tuple[Type[K], Type[V]]:
487 "Extracts the key and value types of a dict type (e.g. returns (`K`, `V`) for `Dict[K, V]`)."
488
489 key_type, value_type = typing.get_args(typ)
490 return key_type, value_type
491
492
493def is_type_annotated(typ: TypeLike) -> bool:
494 "True if the type annotation corresponds to an annotated type (i.e. `Annotated[T, ...]`)."
495
496 return getattr(typ, "__metadata__", None) is not None
497
498
499def get_annotation(data_type: TypeLike, annotation_type: Type[T]) -> Optional[T]:
500 """
501 Returns the first annotation on a data type that matches the expected annotation type.
502
503 :param data_type: The annotated type from which to extract the annotation.
504 :param annotation_type: The annotation class to look for.
505 :returns: The annotation class instance found (if any).
506 """
507
508 metadata = getattr(data_type, "__metadata__", None)
509 if metadata is not None:
510 for annotation in metadata:
511 if isinstance(annotation, annotation_type):
512 return annotation
513
514 return None
515
516
517def unwrap_annotated_type(typ: T) -> T:
518 "Extracts the wrapped type from an annotated type (e.g. returns `T` for `Annotated[T, ...]`)."
519
520 if is_type_annotated(typ):
521 # type is Annotated[T, ...]
522 return typing.get_args(typ)[0]
523 else:
524 # type is a regular type
525 return typ
526
527
528def rewrap_annotated_type(
529 transform: Callable[[Type[S]], Type[T]], typ: Type[S]
530) -> Type[T]:
531 """
532 Un-boxes, transforms and re-boxes an optionally annotated type.
533
534 :param transform: A function that maps an un-annotated type to another type.
535 :param typ: A type to un-box (if necessary), transform, and re-box (if necessary).
536 """
537
538 metadata = getattr(typ, "__metadata__", None)
539 if metadata is not None:
540 # type is Annotated[T, ...]
541 inner_type = typing.get_args(typ)[0]
542 else:
543 # type is a regular type
544 inner_type = typ
545
546 transformed_type = transform(inner_type)
547
548 if metadata is not None:
549 return Annotated[(transformed_type, *metadata)] # type: ignore
550 else:
551 return transformed_type
552
553
554def get_module_classes(module: types.ModuleType) -> List[type]:
555 "Returns all classes declared directly in a module."
556
557 def is_class_member(member: object) -> TypeGuard[type]:
558 return inspect.isclass(member) and member.__module__ == module.__name__
559
560 return [class_type for _, class_type in inspect.getmembers(module, is_class_member)]
561
562
563if sys.version_info >= (3, 9):
564
565 def get_resolved_hints(typ: type) -> Dict[str, type]:
566 return typing.get_type_hints(typ, include_extras=True)
567
568else:
569
570 def get_resolved_hints(typ: type) -> Dict[str, type]:
571 return typing.get_type_hints(typ)
572
573
574def get_class_properties(typ: type) -> Iterable[Tuple[str, type]]:
575 "Returns all properties of a class."
576
577 if is_dataclass_type(typ):
578 return ((field.name, field.type) for field in dataclasses.fields(typ))
579 else:
580 resolved_hints = get_resolved_hints(typ)
581 return resolved_hints.items()
582
583
584def get_class_property(typ: type, name: str) -> Optional[type]:
585 "Looks up the annotated type of a property in a class by its property name."
586
587 for property_name, property_type in get_class_properties(typ):
588 if name == property_name:
589 return property_type
590 return None
591
592
593@dataclasses.dataclass
594class _ROOT:
595 pass
596
597
598def get_referenced_types(
599 typ: TypeLike, module: Optional[types.ModuleType] = None
600) -> Set[type]:
601 """
602 Extracts types directly or indirectly referenced by this type.
603
604 For example, extract `T` from `List[T]`, `Optional[T]` or `Annotated[T, ...]`, `K` and `V` from `Dict[K,V]`,
605 `A` and `B` from `Union[A,B]`.
606
607 :param typ: A type or special form.
608 :param module: The context in which types are evaluated.
609 :returns: Types referenced by the given type or special form.
610 """
611
612 collector = TypeCollector()
613 collector.run(typ, _ROOT, module)
614 return collector.references
615
616
617class TypeCollector:
618 """
619 Collects types directly or indirectly referenced by a type.
620
621 :param graph: The type dependency graph, linking types to types they depend on.
622 """
623
624 graph: Dict[type, Set[type]]
625
626 @property
627 def references(self) -> Set[type]:
628 "Types collected by the type collector."
629
630 dependencies = set()
631 for edges in self.graph.values():
632 dependencies.update(edges)
633 return dependencies
634
635 def __init__(self) -> None:
636 self.graph = {_ROOT: set()}
637
638 def traverse(self, typ: type) -> None:
639 "Finds all dependent types of a type."
640
641 self.run(typ, _ROOT, sys.modules[typ.__module__])
642
643 def traverse_all(self, types: Iterable[type]) -> None:
644 "Finds all dependent types of a list of types."
645
646 for typ in types:
647 self.traverse(typ)
648
649 def run(
650 self,
651 typ: TypeLike,
652 cls: Type[DataclassInstance],
653 module: Optional[types.ModuleType],
654 ) -> None:
655 """
656 Extracts types indirectly referenced by this type.
657
658 For example, extract `T` from `List[T]`, `Optional[T]` or `Annotated[T, ...]`, `K` and `V` from `Dict[K,V]`,
659 `A` and `B` from `Union[A,B]`.
660
661 :param typ: A type or special form.
662 :param cls: A dataclass type being expanded for dependent types.
663 :param module: The context in which types are evaluated.
664 :returns: Types referenced by the given type or special form.
665 """
666
667 if typ is type(None) or typ is Any:
668 return
669
670 if isinstance(typ, type):
671 self.graph[cls].add(typ)
672
673 if typ in self.graph:
674 return
675
676 self.graph[typ] = set()
677
678 metadata = getattr(typ, "__metadata__", None)
679 if metadata is not None:
680 # type is Annotated[T, ...]
681 arg = typing.get_args(typ)[0]
682 return self.run(arg, cls, module)
683
684 # type is a forward reference
685 if isinstance(typ, str) or isinstance(typ, typing.ForwardRef):
686 if module is None:
687 raise ValueError("missing context for evaluating types")
688
689 evaluated_type = evaluate_type(typ, module)
690 return self.run(evaluated_type, cls, module)
691
692 # type is a special form
693 origin = typing.get_origin(typ)
694 if origin in [list, dict, frozenset, set, tuple, Union]:
695 for arg in typing.get_args(typ):
696 self.run(arg, cls, module)
697 return
698 elif origin is Literal:
699 return
700
701 # type is optional or a union type
702 if is_type_optional(typ):
703 return self.run(unwrap_optional_type(typ), cls, module)
704 if is_type_union(typ):
705 for union_type in unwrap_union_types(typ):
706 self.run(union_type, cls, module)
707 return
708
709 # type is a regular type
710 elif is_dataclass_type(typ) or is_type_enum(typ) or isinstance(typ, type):
711 context = sys.modules[typ.__module__]
712 if is_dataclass_type(typ):
713 for field in dataclass_fields(typ):
714 self.run(field.type, typ, context)
715 else:
716 for field_name, field_type in get_resolved_hints(typ).items():
717 self.run(field_type, typ, context)
718 return
719
720 raise TypeError(f"expected: type-like; got: {typ}")
721
722
723if sys.version_info >= (3, 10):
724
725 def get_signature(fn: Callable[..., Any]) -> inspect.Signature:
726 "Extracts the signature of a function."
727
728 return inspect.signature(fn, eval_str=True)
729
730else:
731
732 def get_signature(fn: Callable[..., Any]) -> inspect.Signature:
733 "Extracts the signature of a function."
734
735 return inspect.signature(fn)
736
737
738def is_reserved_property(name: str) -> bool:
739 "True if the name stands for an internal property."
740
741 # filter built-in and special properties
742 if re.match(r"^__.+__$", name):
743 return True
744
745 # filter built-in special names
746 if name in ["_abc_impl"]:
747 return True
748
749 return False
750
751
752def create_module(name: str) -> types.ModuleType:
753 """
754 Creates a new module dynamically at run-time.
755
756 :param name: Fully qualified name of the new module (with dot notation).
757 """
758
759 if name in sys.modules:
760 raise KeyError(f"{name!r} already in sys.modules")
761
762 spec = importlib.machinery.ModuleSpec(name, None)
763 module = importlib.util.module_from_spec(spec)
764 sys.modules[name] = module
765 if spec.loader is not None:
766 spec.loader.exec_module(module)
767 return module
768
769
770if sys.version_info >= (3, 10):
771
772 def create_data_type(class_name: str, fields: List[Tuple[str, type]]) -> type:
773 """
774 Creates a new data-class type dynamically.
775
776 :param class_name: The name of new data-class type.
777 :param fields: A list of fields (and their type) that the new data-class type is expected to have.
778 :returns: The newly created data-class type.
779 """
780
781 # has the `slots` parameter
782 return dataclasses.make_dataclass(class_name, fields, slots=True)
783
784else:
785
786 def create_data_type(class_name: str, fields: List[Tuple[str, type]]) -> type:
787 """
788 Creates a new data-class type dynamically.
789
790 :param class_name: The name of new data-class type.
791 :param fields: A list of fields (and their type) that the new data-class type is expected to have.
792 :returns: The newly created data-class type.
793 """
794
795 cls = dataclasses.make_dataclass(class_name, fields)
796
797 cls_dict = dict(cls.__dict__)
798 field_names = tuple(field.name for field in dataclasses.fields(cls))
799
800 cls_dict["__slots__"] = field_names
801
802 for field_name in field_names:
803 cls_dict.pop(field_name, None)
804 cls_dict.pop("__dict__", None)
805
806 qualname = getattr(cls, "__qualname__", None)
807 cls = type(cls)(cls.__name__, (), cls_dict)
808 if qualname is not None:
809 cls.__qualname__ = qualname
810
811 return cls
812
813
814def create_object(typ: Type[T]) -> T:
815 "Creates an instance of a type."
816
817 if issubclass(typ, Exception):
818 # exception types need special treatment
819 e = typ.__new__(typ)
820 return typing.cast(T, e)
821 else:
822 return object.__new__(typ)
823
824
825if sys.version_info >= (3, 9):
826 TypeOrGeneric = Union[type, types.GenericAlias]
827
828else:
829 TypeOrGeneric = object
830
831
832def is_generic_instance(obj: Any, typ: TypeLike) -> bool:
833 """
834 Returns whether an object is an instance of a generic class, a standard class or of a subclass thereof.
835
836 This function checks the following items recursively:
837 * items of a list
838 * keys and values of a dictionary
839 * members of a set
840 * items of a tuple
841 * members of a union type
842
843 :param obj: The (possibly generic container) object to check recursively.
844 :param typ: The expected type of the object.
845 """
846
847 if isinstance(typ, typing.ForwardRef):
848 fwd: typing.ForwardRef = typ
849 identifier = fwd.__forward_arg__
850 typ = eval(identifier)
851 if isinstance(typ, type):
852 return isinstance(obj, typ)
853 else:
854 return False
855
856 # generic types (e.g. list, dict, set, etc.)
857 origin_type = typing.get_origin(typ)
858 if origin_type is list:
859 if not isinstance(obj, list):
860 return False
861 (list_item_type,) = typing.get_args(typ) # unpack single tuple element
862 list_obj: list = obj
863 return all(is_generic_instance(item, list_item_type) for item in list_obj)
864 elif origin_type is dict:
865 if not isinstance(obj, dict):
866 return False
867 key_type, value_type = typing.get_args(typ)
868 dict_obj: dict = obj
869 return all(
870 is_generic_instance(key, key_type)
871 and is_generic_instance(value, value_type)
872 for key, value in dict_obj.items()
873 )
874 elif origin_type is set:
875 if not isinstance(obj, set):
876 return False
877 (set_member_type,) = typing.get_args(typ) # unpack single tuple element
878 set_obj: set = obj
879 return all(is_generic_instance(item, set_member_type) for item in set_obj)
880 elif origin_type is tuple:
881 if not isinstance(obj, tuple):
882 return False
883 return all(
884 is_generic_instance(item, tuple_item_type)
885 for tuple_item_type, item in zip(
886 (tuple_item_type for tuple_item_type in typing.get_args(typ)),
887 (item for item in obj),
888 )
889 )
890 elif origin_type is Union:
891 return any(
892 is_generic_instance(obj, member_type)
893 for member_type in typing.get_args(typ)
894 )
895 elif isinstance(typ, type):
896 return isinstance(obj, typ)
897 else:
898 raise TypeError(f"expected `type` but got: {typ}")
899
900
901class RecursiveChecker:
902 _pred: Optional[Callable[[type, Any], bool]]
903
904 def __init__(self, pred: Callable[[type, Any], bool]) -> None:
905 """
906 Creates a checker to verify if a predicate applies to all nested member properties of an object recursively.
907
908 :param pred: The predicate to test on member properties. Takes a property type and a property value.
909 """
910
911 self._pred = pred
912
913 def pred(self, typ: type, obj: Any) -> bool:
914 "Acts as a workaround for the type checker mypy."
915
916 assert self._pred is not None
917 return self._pred(typ, obj)
918
919 def check(self, typ: TypeLike, obj: Any) -> bool:
920 """
921 Checks if a predicate applies to all nested member properties of an object recursively.
922
923 :param typ: The type to recurse into.
924 :param obj: The object to inspect recursively. Must be an instance of the given type.
925 :returns: True if all member properties pass the filter predicate.
926 """
927
928 # check for well-known types
929 if (
930 typ is type(None)
931 or typ is bool
932 or typ is int
933 or typ is float
934 or typ is str
935 or typ is bytes
936 or typ is datetime.datetime
937 or typ is datetime.date
938 or typ is datetime.time
939 or typ is uuid.UUID
940 ):
941 return self.pred(typing.cast(type, typ), obj)
942
943 # generic types (e.g. list, dict, set, etc.)
944 origin_type = typing.get_origin(typ)
945 if origin_type is list:
946 if not isinstance(obj, list):
947 raise TypeError(f"expected `list` but got: {obj}")
948 (list_item_type,) = typing.get_args(typ) # unpack single tuple element
949 list_obj: list = obj
950 return all(self.check(list_item_type, item) for item in list_obj)
951 elif origin_type is dict:
952 if not isinstance(obj, dict):
953 raise TypeError(f"expected `dict` but got: {obj}")
954 key_type, value_type = typing.get_args(typ)
955 dict_obj: dict = obj
956 return all(self.check(value_type, item) for item in dict_obj.values())
957 elif origin_type is set:
958 if not isinstance(obj, set):
959 raise TypeError(f"expected `set` but got: {obj}")
960 (set_member_type,) = typing.get_args(typ) # unpack single tuple element
961 set_obj: set = obj
962 return all(self.check(set_member_type, item) for item in set_obj)
963 elif origin_type is tuple:
964 if not isinstance(obj, tuple):
965 raise TypeError(f"expected `tuple` but got: {obj}")
966 return all(
967 self.check(tuple_item_type, item)
968 for tuple_item_type, item in zip(
969 (tuple_item_type for tuple_item_type in typing.get_args(typ)),
970 (item for item in obj),
971 )
972 )
973 elif origin_type is Union:
974 return self.pred(typ, obj) # type: ignore[arg-type]
975
976 if not inspect.isclass(typ):
977 raise TypeError(f"expected `type` but got: {typ}")
978
979 # enumeration type
980 if issubclass(typ, enum.Enum):
981 if not isinstance(obj, enum.Enum):
982 raise TypeError(f"expected `{typ}` but got: {obj}")
983 return self.pred(typ, obj)
984
985 # class types with properties
986 if is_named_tuple_type(typ):
987 if not isinstance(obj, tuple):
988 raise TypeError(f"expected `NamedTuple` but got: {obj}")
989 return all(
990 self.check(field_type, getattr(obj, field_name))
991 for field_name, field_type in typing.get_type_hints(typ).items()
992 )
993 elif is_dataclass_type(typ):
994 if not isinstance(obj, typ):
995 raise TypeError(f"expected `{typ}` but got: {obj}")
996 resolved_hints = get_resolved_hints(typ)
997 return all(
998 self.check(resolved_hints[field.name], getattr(obj, field.name))
999 for field in dataclasses.fields(typ)
1000 )
1001 else:
1002 if not isinstance(obj, typ):
1003 raise TypeError(f"expected `{typ}` but got: {obj}")
1004 return all(
1005 self.check(property_type, getattr(obj, property_name))
1006 for property_name, property_type in get_class_properties(typ)
1007 )
1008
1009
1010def check_recursive(
1011 obj: object,
1012 /,
1013 *,
1014 pred: Optional[Callable[[type, Any], bool]] = None,
1015 type_pred: Optional[Callable[[type], bool]] = None,
1016 value_pred: Optional[Callable[[Any], bool]] = None,
1017) -> bool:
1018 """
1019 Checks if a predicate applies to all nested member properties of an object recursively.
1020
1021 :param obj: The object to inspect recursively.
1022 :param pred: The predicate to test on member properties. Takes a property type and a property value.
1023 :param type_pred: Constrains the check to properties of an expected type. Properties of other types pass automatically.
1024 :param value_pred: Verifies a condition on member property values (of an expected type).
1025 :returns: True if all member properties pass the filter predicate(s).
1026 """
1027
1028 if type_pred is not None and value_pred is not None:
1029 if pred is not None:
1030 raise TypeError(
1031 "filter predicate not permitted when type and value predicates are present"
1032 )
1033
1034 type_p: Callable[[Type[T]], bool] = type_pred
1035 value_p: Callable[[T], bool] = value_pred
1036 pred = lambda typ, obj: not type_p(typ) or value_p(obj) # noqa: E731
1037
1038 elif value_pred is not None:
1039 if pred is not None:
1040 raise TypeError(
1041 "filter predicate not permitted when value predicate is present"
1042 )
1043
1044 value_only_p: Callable[[T], bool] = value_pred
1045 pred = lambda typ, obj: value_only_p(obj) # noqa: E731
1046
1047 elif type_pred is not None:
1048 raise TypeError("value predicate required when type predicate is present")
1049
1050 elif pred is None:
1051 pred = lambda typ, obj: True # noqa: E731
1052
1053 return RecursiveChecker(pred).check(type(obj), obj)