Debian Codegraph @

beanie/odm/utils/typing.py

raw
1 import inspect
2 from typing import Any, get_args, get_origin
3
4 from beanie.odm.fields import IndexedAnnotation
5
6 from .pydantic import get_field_type
7
8
9 def extract_id_class(annotation) -> type[Any]:
10 if get_origin(annotation) is not None:
11 try:
12 annotation = next(
13 arg for arg in get_args(annotation) if arg is not type(None)
14 )
15 except StopIteration:
16 annotation = None
17 if inspect.isclass(annotation):
18 return annotation
19 raise ValueError(f"Unknown annotation: {annotation}")
20
21
22 def get_index_attributes(field) -> tuple[int, dict[str, Any]] | None:
23 """Gets the index attributes from the field, if it is indexed.
24
25 :param field: The field to get the index attributes from.
26
27 :return: The index attributes, if the field is indexed. Otherwise, None.
28 """
29 # For fields that are directly typed with `Indexed()`, the type will have
30 # an `_indexed` attribute.
31 field_type = get_field_type(field)
32 if hasattr(field_type, "_indexed"):
33 return getattr(field_type, "_indexed", None)
34
35 # For fields that are use `Indexed` within `Annotated`, the field will have
36 # metadata that might contain an `IndexedAnnotation` instance.
37 # In Pydantic 2, the field has a `metadata` attribute with
38 # the annotations.
39 metadata = getattr(field, "metadata", None)
40
41 if metadata is None:
42 return None
43
44 try:
45 iter(metadata)
46 except TypeError:
47 return None
48
49 indexed_annotation = next(
50 (
51 annotation
52 for annotation in metadata
53 if isinstance(annotation, IndexedAnnotation)
54 ),
55 None,
56 )
57
58 return getattr(indexed_annotation, "_indexed", None)
59
60
61 def is_generic_alias(obj: Any) -> bool:
62 """Check if the object is a typing or built-in generic alias (e.g., list[str], List[int]).
63
64 :param obj: An object instance.
65
66 :return: True if obj is a typing or built-in generic alias, False otherwise.
67 """
68
69 # Check built-in generic aliases (e.g. list[str])
70 try:
71 from types import GenericAlias
72
73 if isinstance(obj, GenericAlias):
74 return True
75 except ImportError:
76 pass # Python < 3.9
77
78 # Check legacy typing generics (e.g. typing.List[str])
79 try:
80 from typing import _GenericAlias # type: ignore[attr-defined]
81
82 if isinstance(obj, _GenericAlias):
83 return True
84 except ImportError:
85 pass
86
87 return False