SQLAlchemy 2.1.0b2__cp313-cp313t-win_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (270) hide show
  1. sqlalchemy/__init__.py +298 -0
  2. sqlalchemy/connectors/__init__.py +18 -0
  3. sqlalchemy/connectors/aioodbc.py +171 -0
  4. sqlalchemy/connectors/asyncio.py +476 -0
  5. sqlalchemy/connectors/pyodbc.py +250 -0
  6. sqlalchemy/dialects/__init__.py +62 -0
  7. sqlalchemy/dialects/_typing.py +30 -0
  8. sqlalchemy/dialects/mssql/__init__.py +89 -0
  9. sqlalchemy/dialects/mssql/aioodbc.py +63 -0
  10. sqlalchemy/dialects/mssql/base.py +4166 -0
  11. sqlalchemy/dialects/mssql/information_schema.py +285 -0
  12. sqlalchemy/dialects/mssql/json.py +140 -0
  13. sqlalchemy/dialects/mssql/mssqlpython.py +220 -0
  14. sqlalchemy/dialects/mssql/provision.py +196 -0
  15. sqlalchemy/dialects/mssql/pymssql.py +126 -0
  16. sqlalchemy/dialects/mssql/pyodbc.py +698 -0
  17. sqlalchemy/dialects/mysql/__init__.py +106 -0
  18. sqlalchemy/dialects/mysql/_mariadb_shim.py +312 -0
  19. sqlalchemy/dialects/mysql/aiomysql.py +226 -0
  20. sqlalchemy/dialects/mysql/asyncmy.py +214 -0
  21. sqlalchemy/dialects/mysql/base.py +3877 -0
  22. sqlalchemy/dialects/mysql/cymysql.py +106 -0
  23. sqlalchemy/dialects/mysql/dml.py +279 -0
  24. sqlalchemy/dialects/mysql/enumerated.py +277 -0
  25. sqlalchemy/dialects/mysql/expression.py +146 -0
  26. sqlalchemy/dialects/mysql/json.py +92 -0
  27. sqlalchemy/dialects/mysql/mariadb.py +67 -0
  28. sqlalchemy/dialects/mysql/mariadbconnector.py +330 -0
  29. sqlalchemy/dialects/mysql/mysqlconnector.py +296 -0
  30. sqlalchemy/dialects/mysql/mysqldb.py +312 -0
  31. sqlalchemy/dialects/mysql/provision.py +153 -0
  32. sqlalchemy/dialects/mysql/pymysql.py +157 -0
  33. sqlalchemy/dialects/mysql/pyodbc.py +156 -0
  34. sqlalchemy/dialects/mysql/reflection.py +724 -0
  35. sqlalchemy/dialects/mysql/reserved_words.py +570 -0
  36. sqlalchemy/dialects/mysql/types.py +845 -0
  37. sqlalchemy/dialects/oracle/__init__.py +85 -0
  38. sqlalchemy/dialects/oracle/base.py +3977 -0
  39. sqlalchemy/dialects/oracle/cx_oracle.py +1601 -0
  40. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  41. sqlalchemy/dialects/oracle/json.py +158 -0
  42. sqlalchemy/dialects/oracle/oracledb.py +909 -0
  43. sqlalchemy/dialects/oracle/provision.py +288 -0
  44. sqlalchemy/dialects/oracle/types.py +367 -0
  45. sqlalchemy/dialects/oracle/vector.py +368 -0
  46. sqlalchemy/dialects/postgresql/__init__.py +171 -0
  47. sqlalchemy/dialects/postgresql/_psycopg_common.py +229 -0
  48. sqlalchemy/dialects/postgresql/array.py +534 -0
  49. sqlalchemy/dialects/postgresql/asyncpg.py +1323 -0
  50. sqlalchemy/dialects/postgresql/base.py +5789 -0
  51. sqlalchemy/dialects/postgresql/bitstring.py +327 -0
  52. sqlalchemy/dialects/postgresql/dml.py +360 -0
  53. sqlalchemy/dialects/postgresql/ext.py +593 -0
  54. sqlalchemy/dialects/postgresql/hstore.py +423 -0
  55. sqlalchemy/dialects/postgresql/json.py +408 -0
  56. sqlalchemy/dialects/postgresql/named_types.py +521 -0
  57. sqlalchemy/dialects/postgresql/operators.py +130 -0
  58. sqlalchemy/dialects/postgresql/pg8000.py +670 -0
  59. sqlalchemy/dialects/postgresql/pg_catalog.py +344 -0
  60. sqlalchemy/dialects/postgresql/provision.py +184 -0
  61. sqlalchemy/dialects/postgresql/psycopg.py +799 -0
  62. sqlalchemy/dialects/postgresql/psycopg2.py +860 -0
  63. sqlalchemy/dialects/postgresql/psycopg2cffi.py +61 -0
  64. sqlalchemy/dialects/postgresql/ranges.py +1002 -0
  65. sqlalchemy/dialects/postgresql/types.py +388 -0
  66. sqlalchemy/dialects/sqlite/__init__.py +57 -0
  67. sqlalchemy/dialects/sqlite/aiosqlite.py +321 -0
  68. sqlalchemy/dialects/sqlite/base.py +3063 -0
  69. sqlalchemy/dialects/sqlite/dml.py +279 -0
  70. sqlalchemy/dialects/sqlite/json.py +100 -0
  71. sqlalchemy/dialects/sqlite/provision.py +229 -0
  72. sqlalchemy/dialects/sqlite/pysqlcipher.py +161 -0
  73. sqlalchemy/dialects/sqlite/pysqlite.py +754 -0
  74. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  75. sqlalchemy/engine/__init__.py +62 -0
  76. sqlalchemy/engine/_processors_cy.cp313t-win_arm64.pyd +0 -0
  77. sqlalchemy/engine/_processors_cy.py +92 -0
  78. sqlalchemy/engine/_result_cy.cp313t-win_arm64.pyd +0 -0
  79. sqlalchemy/engine/_result_cy.py +633 -0
  80. sqlalchemy/engine/_row_cy.cp313t-win_arm64.pyd +0 -0
  81. sqlalchemy/engine/_row_cy.py +232 -0
  82. sqlalchemy/engine/_util_cy.cp313t-win_arm64.pyd +0 -0
  83. sqlalchemy/engine/_util_cy.py +136 -0
  84. sqlalchemy/engine/base.py +3354 -0
  85. sqlalchemy/engine/characteristics.py +155 -0
  86. sqlalchemy/engine/create.py +877 -0
  87. sqlalchemy/engine/cursor.py +2421 -0
  88. sqlalchemy/engine/default.py +2402 -0
  89. sqlalchemy/engine/events.py +965 -0
  90. sqlalchemy/engine/interfaces.py +3495 -0
  91. sqlalchemy/engine/mock.py +134 -0
  92. sqlalchemy/engine/processors.py +82 -0
  93. sqlalchemy/engine/reflection.py +2100 -0
  94. sqlalchemy/engine/result.py +1966 -0
  95. sqlalchemy/engine/row.py +397 -0
  96. sqlalchemy/engine/strategies.py +16 -0
  97. sqlalchemy/engine/url.py +922 -0
  98. sqlalchemy/engine/util.py +156 -0
  99. sqlalchemy/event/__init__.py +26 -0
  100. sqlalchemy/event/api.py +220 -0
  101. sqlalchemy/event/attr.py +674 -0
  102. sqlalchemy/event/base.py +472 -0
  103. sqlalchemy/event/legacy.py +258 -0
  104. sqlalchemy/event/registry.py +390 -0
  105. sqlalchemy/events.py +17 -0
  106. sqlalchemy/exc.py +922 -0
  107. sqlalchemy/ext/__init__.py +11 -0
  108. sqlalchemy/ext/associationproxy.py +2072 -0
  109. sqlalchemy/ext/asyncio/__init__.py +29 -0
  110. sqlalchemy/ext/asyncio/base.py +281 -0
  111. sqlalchemy/ext/asyncio/engine.py +1487 -0
  112. sqlalchemy/ext/asyncio/exc.py +21 -0
  113. sqlalchemy/ext/asyncio/result.py +994 -0
  114. sqlalchemy/ext/asyncio/scoping.py +1679 -0
  115. sqlalchemy/ext/asyncio/session.py +2007 -0
  116. sqlalchemy/ext/automap.py +1701 -0
  117. sqlalchemy/ext/baked.py +559 -0
  118. sqlalchemy/ext/compiler.py +600 -0
  119. sqlalchemy/ext/declarative/__init__.py +65 -0
  120. sqlalchemy/ext/declarative/extensions.py +560 -0
  121. sqlalchemy/ext/horizontal_shard.py +481 -0
  122. sqlalchemy/ext/hybrid.py +1877 -0
  123. sqlalchemy/ext/indexable.py +364 -0
  124. sqlalchemy/ext/instrumentation.py +450 -0
  125. sqlalchemy/ext/mutable.py +1081 -0
  126. sqlalchemy/ext/orderinglist.py +439 -0
  127. sqlalchemy/ext/serializer.py +185 -0
  128. sqlalchemy/future/__init__.py +16 -0
  129. sqlalchemy/future/engine.py +15 -0
  130. sqlalchemy/inspection.py +174 -0
  131. sqlalchemy/log.py +283 -0
  132. sqlalchemy/orm/__init__.py +176 -0
  133. sqlalchemy/orm/_orm_constructors.py +2694 -0
  134. sqlalchemy/orm/_typing.py +179 -0
  135. sqlalchemy/orm/attributes.py +2868 -0
  136. sqlalchemy/orm/base.py +976 -0
  137. sqlalchemy/orm/bulk_persistence.py +2152 -0
  138. sqlalchemy/orm/clsregistry.py +582 -0
  139. sqlalchemy/orm/collections.py +1568 -0
  140. sqlalchemy/orm/context.py +3471 -0
  141. sqlalchemy/orm/decl_api.py +2280 -0
  142. sqlalchemy/orm/decl_base.py +2309 -0
  143. sqlalchemy/orm/dependency.py +1306 -0
  144. sqlalchemy/orm/descriptor_props.py +1183 -0
  145. sqlalchemy/orm/dynamic.py +307 -0
  146. sqlalchemy/orm/evaluator.py +379 -0
  147. sqlalchemy/orm/events.py +3386 -0
  148. sqlalchemy/orm/exc.py +237 -0
  149. sqlalchemy/orm/identity.py +302 -0
  150. sqlalchemy/orm/instrumentation.py +746 -0
  151. sqlalchemy/orm/interfaces.py +1589 -0
  152. sqlalchemy/orm/loading.py +1684 -0
  153. sqlalchemy/orm/mapped_collection.py +557 -0
  154. sqlalchemy/orm/mapper.py +4411 -0
  155. sqlalchemy/orm/path_registry.py +829 -0
  156. sqlalchemy/orm/persistence.py +1789 -0
  157. sqlalchemy/orm/properties.py +973 -0
  158. sqlalchemy/orm/query.py +3528 -0
  159. sqlalchemy/orm/relationships.py +3570 -0
  160. sqlalchemy/orm/scoping.py +2232 -0
  161. sqlalchemy/orm/session.py +5403 -0
  162. sqlalchemy/orm/state.py +1175 -0
  163. sqlalchemy/orm/state_changes.py +196 -0
  164. sqlalchemy/orm/strategies.py +3492 -0
  165. sqlalchemy/orm/strategy_options.py +2562 -0
  166. sqlalchemy/orm/sync.py +164 -0
  167. sqlalchemy/orm/unitofwork.py +798 -0
  168. sqlalchemy/orm/util.py +2438 -0
  169. sqlalchemy/orm/writeonly.py +694 -0
  170. sqlalchemy/pool/__init__.py +41 -0
  171. sqlalchemy/pool/base.py +1522 -0
  172. sqlalchemy/pool/events.py +375 -0
  173. sqlalchemy/pool/impl.py +582 -0
  174. sqlalchemy/py.typed +0 -0
  175. sqlalchemy/schema.py +74 -0
  176. sqlalchemy/sql/__init__.py +156 -0
  177. sqlalchemy/sql/_annotated_cols.py +397 -0
  178. sqlalchemy/sql/_dml_constructors.py +132 -0
  179. sqlalchemy/sql/_elements_constructors.py +2164 -0
  180. sqlalchemy/sql/_orm_types.py +20 -0
  181. sqlalchemy/sql/_selectable_constructors.py +840 -0
  182. sqlalchemy/sql/_typing.py +487 -0
  183. sqlalchemy/sql/_util_cy.cp313t-win_arm64.pyd +0 -0
  184. sqlalchemy/sql/_util_cy.py +127 -0
  185. sqlalchemy/sql/annotation.py +590 -0
  186. sqlalchemy/sql/base.py +2699 -0
  187. sqlalchemy/sql/cache_key.py +1066 -0
  188. sqlalchemy/sql/coercions.py +1373 -0
  189. sqlalchemy/sql/compiler.py +8327 -0
  190. sqlalchemy/sql/crud.py +1815 -0
  191. sqlalchemy/sql/ddl.py +1928 -0
  192. sqlalchemy/sql/default_comparator.py +654 -0
  193. sqlalchemy/sql/dml.py +1977 -0
  194. sqlalchemy/sql/elements.py +6033 -0
  195. sqlalchemy/sql/events.py +458 -0
  196. sqlalchemy/sql/expression.py +172 -0
  197. sqlalchemy/sql/functions.py +2305 -0
  198. sqlalchemy/sql/lambdas.py +1443 -0
  199. sqlalchemy/sql/naming.py +209 -0
  200. sqlalchemy/sql/operators.py +2897 -0
  201. sqlalchemy/sql/roles.py +332 -0
  202. sqlalchemy/sql/schema.py +6703 -0
  203. sqlalchemy/sql/selectable.py +7553 -0
  204. sqlalchemy/sql/sqltypes.py +4093 -0
  205. sqlalchemy/sql/traversals.py +1042 -0
  206. sqlalchemy/sql/type_api.py +2446 -0
  207. sqlalchemy/sql/util.py +1495 -0
  208. sqlalchemy/sql/visitors.py +1157 -0
  209. sqlalchemy/testing/__init__.py +96 -0
  210. sqlalchemy/testing/assertions.py +1007 -0
  211. sqlalchemy/testing/assertsql.py +519 -0
  212. sqlalchemy/testing/asyncio.py +128 -0
  213. sqlalchemy/testing/config.py +440 -0
  214. sqlalchemy/testing/engines.py +483 -0
  215. sqlalchemy/testing/entities.py +117 -0
  216. sqlalchemy/testing/exclusions.py +476 -0
  217. sqlalchemy/testing/fixtures/__init__.py +30 -0
  218. sqlalchemy/testing/fixtures/base.py +384 -0
  219. sqlalchemy/testing/fixtures/mypy.py +247 -0
  220. sqlalchemy/testing/fixtures/orm.py +227 -0
  221. sqlalchemy/testing/fixtures/sql.py +538 -0
  222. sqlalchemy/testing/pickleable.py +155 -0
  223. sqlalchemy/testing/plugin/__init__.py +6 -0
  224. sqlalchemy/testing/plugin/bootstrap.py +51 -0
  225. sqlalchemy/testing/plugin/plugin_base.py +828 -0
  226. sqlalchemy/testing/plugin/pytestplugin.py +892 -0
  227. sqlalchemy/testing/profiling.py +329 -0
  228. sqlalchemy/testing/provision.py +613 -0
  229. sqlalchemy/testing/requirements.py +1978 -0
  230. sqlalchemy/testing/schema.py +198 -0
  231. sqlalchemy/testing/suite/__init__.py +19 -0
  232. sqlalchemy/testing/suite/test_cte.py +237 -0
  233. sqlalchemy/testing/suite/test_ddl.py +420 -0
  234. sqlalchemy/testing/suite/test_dialect.py +776 -0
  235. sqlalchemy/testing/suite/test_insert.py +630 -0
  236. sqlalchemy/testing/suite/test_reflection.py +3557 -0
  237. sqlalchemy/testing/suite/test_results.py +660 -0
  238. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  239. sqlalchemy/testing/suite/test_select.py +2112 -0
  240. sqlalchemy/testing/suite/test_sequence.py +317 -0
  241. sqlalchemy/testing/suite/test_table_via_select.py +686 -0
  242. sqlalchemy/testing/suite/test_types.py +2271 -0
  243. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  244. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  245. sqlalchemy/testing/util.py +535 -0
  246. sqlalchemy/testing/warnings.py +52 -0
  247. sqlalchemy/types.py +76 -0
  248. sqlalchemy/util/__init__.py +158 -0
  249. sqlalchemy/util/_collections.py +688 -0
  250. sqlalchemy/util/_collections_cy.cp313t-win_arm64.pyd +0 -0
  251. sqlalchemy/util/_collections_cy.pxd +8 -0
  252. sqlalchemy/util/_collections_cy.py +516 -0
  253. sqlalchemy/util/_has_cython.py +46 -0
  254. sqlalchemy/util/_immutabledict_cy.cp313t-win_arm64.pyd +0 -0
  255. sqlalchemy/util/_immutabledict_cy.py +240 -0
  256. sqlalchemy/util/compat.py +299 -0
  257. sqlalchemy/util/concurrency.py +322 -0
  258. sqlalchemy/util/cython.py +79 -0
  259. sqlalchemy/util/deprecations.py +401 -0
  260. sqlalchemy/util/langhelpers.py +2320 -0
  261. sqlalchemy/util/preloaded.py +152 -0
  262. sqlalchemy/util/queue.py +304 -0
  263. sqlalchemy/util/tool_support.py +201 -0
  264. sqlalchemy/util/topological.py +120 -0
  265. sqlalchemy/util/typing.py +711 -0
  266. sqlalchemy-2.1.0b2.dist-info/METADATA +269 -0
  267. sqlalchemy-2.1.0b2.dist-info/RECORD +270 -0
  268. sqlalchemy-2.1.0b2.dist-info/WHEEL +5 -0
  269. sqlalchemy-2.1.0b2.dist-info/licenses/LICENSE +19 -0
  270. sqlalchemy-2.1.0b2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,711 @@
1
+ # util/typing.py
2
+ # Copyright (C) 2022-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ # mypy: allow-untyped-defs, allow-untyped-calls
8
+
9
+ from __future__ import annotations
10
+
11
+ import builtins
12
+ from collections import deque
13
+ import collections.abc as collections_abc
14
+ import re
15
+ import sys
16
+ from types import NoneType
17
+ import typing
18
+ from typing import Any
19
+ from typing import Callable
20
+ from typing import Dict
21
+ from typing import ForwardRef
22
+ from typing import Generic
23
+ from typing import get_args
24
+ from typing import get_origin
25
+ from typing import Iterable
26
+ from typing import Literal
27
+ from typing import Mapping
28
+ from typing import NewType
29
+ from typing import NoReturn
30
+ from typing import Optional
31
+ from typing import overload
32
+ from typing import Protocol
33
+ from typing import Set
34
+ from typing import Tuple
35
+ from typing import Type
36
+ from typing import TYPE_CHECKING
37
+ from typing import TypeGuard
38
+ from typing import Union
39
+
40
+ import typing_extensions
41
+
42
+ from . import compat
43
+
44
+ if True: # zimports removes the tailing comments
45
+ from typing_extensions import (
46
+ dataclass_transform as dataclass_transform, # 3.11,
47
+ )
48
+ from typing_extensions import NotRequired as NotRequired # 3.11
49
+ from typing_extensions import TypeVarTuple as TypeVarTuple # 3.11
50
+ from typing_extensions import Self as Self # 3.11
51
+ from typing_extensions import TypeAliasType as TypeAliasType # 3.12
52
+ from typing_extensions import Unpack as Unpack # 3.11
53
+ from typing_extensions import Never as Never # 3.11
54
+ from typing_extensions import LiteralString as LiteralString # 3.11
55
+ from typing_extensions import TypeVar as TypeVar # 3.13 for default
56
+
57
+
58
+ _T = TypeVar("_T", bound=Any)
59
+ _KT = TypeVar("_KT")
60
+ _KT_co = TypeVar("_KT_co", covariant=True)
61
+ _KT_contra = TypeVar("_KT_contra", contravariant=True)
62
+ _VT = TypeVar("_VT")
63
+ _VT_co = TypeVar("_VT_co", covariant=True)
64
+
65
+ TupleAny = Tuple[Any, ...]
66
+
67
+
68
+ def is_fwd_none(typ: Any) -> bool:
69
+ return isinstance(typ, ForwardRef) and typ.__forward_arg__ == "None"
70
+
71
+
72
+ _AnnotationScanType = Union[
73
+ Type[Any], str, ForwardRef, NewType, TypeAliasType, "GenericProtocol[Any]"
74
+ ]
75
+
76
+ _MatchedOnType = Union[
77
+ "GenericProtocol[Any]", TypeAliasType, NewType, Type[Any]
78
+ ]
79
+
80
+
81
+ class ArgsTypeProtocol(Protocol):
82
+ """protocol for types that have ``__args__``
83
+
84
+ there's no public interface for this AFAIK
85
+
86
+ """
87
+
88
+ __args__: Tuple[_AnnotationScanType, ...]
89
+
90
+
91
+ class GenericProtocol(Protocol[_T]):
92
+ """protocol for generic types.
93
+
94
+ this since Python.typing _GenericAlias is private
95
+
96
+ """
97
+
98
+ __args__: Tuple[_AnnotationScanType, ...]
99
+ __origin__: Type[_T]
100
+
101
+ # Python's builtin _GenericAlias has this method, however builtins like
102
+ # list, dict, etc. do not, even though they have ``__origin__`` and
103
+ # ``__args__``
104
+ #
105
+ # def copy_with(self, params: Tuple[_AnnotationScanType, ...]) -> Type[_T]:
106
+ # ...
107
+
108
+
109
+ # copied from TypeShed, required in order to implement
110
+ # MutableMapping.update()
111
+ class SupportsKeysAndGetItem(Protocol[_KT, _VT_co]):
112
+ def keys(self) -> Iterable[_KT]: ...
113
+
114
+ def __getitem__(self, __k: _KT) -> _VT_co: ...
115
+
116
+
117
+ # work around https://github.com/microsoft/pyright/issues/3025
118
+ _LiteralStar = Literal["*"]
119
+
120
+
121
+ def de_stringify_annotation(
122
+ cls: Type[Any],
123
+ annotation: _AnnotationScanType,
124
+ originating_module: str,
125
+ locals_: Mapping[str, Any],
126
+ *,
127
+ str_cleanup_fn: Optional[Callable[[str, str], str]] = None,
128
+ include_generic: bool = False,
129
+ _already_seen: Optional[Set[Any]] = None,
130
+ ) -> Type[Any]:
131
+ """Resolve annotations that may be string based into real objects.
132
+
133
+ This is particularly important if a module defines "from __future__ import
134
+ annotations", as everything inside of __annotations__ is a string. We want
135
+ to at least have generic containers like ``Mapped``, ``Union``, ``List``,
136
+ etc.
137
+
138
+ """
139
+ # looked at typing.get_type_hints(), looked at pydantic. We need much
140
+ # less here, and we here try to not use any private typing internals
141
+ # or construct ForwardRef objects which is documented as something
142
+ # that should be avoided.
143
+
144
+ original_annotation = annotation
145
+
146
+ if is_fwd_ref(annotation):
147
+ annotation = annotation.__forward_arg__
148
+
149
+ if isinstance(annotation, str):
150
+ if str_cleanup_fn:
151
+ annotation = str_cleanup_fn(annotation, originating_module)
152
+
153
+ annotation = eval_expression(
154
+ annotation, originating_module, locals_=locals_, in_class=cls
155
+ )
156
+
157
+ if (
158
+ include_generic
159
+ and is_generic(annotation)
160
+ and not is_literal(annotation)
161
+ ):
162
+ if _already_seen is None:
163
+ _already_seen = set()
164
+
165
+ if annotation in _already_seen:
166
+ # only occurs recursively. outermost return type
167
+ # will always be Type.
168
+ # the element here will be either ForwardRef or
169
+ # Optional[ForwardRef]
170
+ return original_annotation # type: ignore
171
+ else:
172
+ _already_seen.add(annotation)
173
+
174
+ elements = tuple(
175
+ de_stringify_annotation(
176
+ cls,
177
+ elem,
178
+ originating_module,
179
+ locals_,
180
+ str_cleanup_fn=str_cleanup_fn,
181
+ include_generic=include_generic,
182
+ _already_seen=_already_seen,
183
+ )
184
+ for elem in annotation.__args__
185
+ )
186
+
187
+ return _copy_generic_annotation_with(annotation, elements)
188
+
189
+ return annotation # type: ignore
190
+
191
+
192
+ def fixup_container_fwd_refs(
193
+ type_: _AnnotationScanType,
194
+ ) -> _AnnotationScanType:
195
+ """Correct dict['x', 'y'] into dict[ForwardRef('x'), ForwardRef('y')]
196
+ and similar for list, set
197
+
198
+ """
199
+
200
+ if (
201
+ is_generic(type_)
202
+ and get_origin(type_)
203
+ in (
204
+ dict,
205
+ set,
206
+ list,
207
+ collections_abc.MutableSet,
208
+ collections_abc.MutableMapping,
209
+ collections_abc.MutableSequence,
210
+ collections_abc.Mapping,
211
+ collections_abc.Sequence,
212
+ )
213
+ # fight, kick and scream to struggle to tell the difference between
214
+ # dict[] and typing.Dict[] which DO NOT compare the same and DO NOT
215
+ # behave the same yet there is NO WAY to distinguish between which type
216
+ # it is using public attributes
217
+ and not re.match(
218
+ "typing.(?:Dict|List|Set|.*Mapping|.*Sequence|.*Set)", repr(type_)
219
+ )
220
+ ):
221
+ # compat with py3.10 and earlier
222
+ return get_origin(type_).__class_getitem__( # type: ignore
223
+ tuple(
224
+ [
225
+ ForwardRef(elem) if isinstance(elem, str) else elem
226
+ for elem in get_args(type_)
227
+ ]
228
+ )
229
+ )
230
+ return type_
231
+
232
+
233
+ def _copy_generic_annotation_with(
234
+ annotation: GenericProtocol[_T], elements: Tuple[_AnnotationScanType, ...]
235
+ ) -> Type[_T]:
236
+ if hasattr(annotation, "copy_with"):
237
+ # List, Dict, etc. real generics
238
+ return annotation.copy_with(elements) # type: ignore
239
+ else:
240
+ # Python builtins list, dict, etc.
241
+ return annotation.__origin__[elements] # type: ignore
242
+
243
+
244
+ def eval_expression(
245
+ expression: str,
246
+ module_name: str,
247
+ *,
248
+ locals_: Optional[Mapping[str, Any]] = None,
249
+ in_class: Optional[Type[Any]] = None,
250
+ ) -> Any:
251
+ try:
252
+ base_globals: Dict[str, Any] = sys.modules[module_name].__dict__
253
+ except KeyError as ke:
254
+ raise NameError(
255
+ f"Module {module_name} isn't present in sys.modules; can't "
256
+ f"evaluate expression {expression}"
257
+ ) from ke
258
+
259
+ try:
260
+ if in_class is not None:
261
+ cls_namespace = dict(in_class.__dict__)
262
+ cls_namespace.setdefault(in_class.__name__, in_class)
263
+
264
+ # see #10899. We want the locals/globals to take precedence
265
+ # over the class namespace in this context, even though this
266
+ # is not the usual way variables would resolve.
267
+ cls_namespace.update(base_globals)
268
+
269
+ annotation = eval(expression, cls_namespace, locals_)
270
+ else:
271
+ annotation = eval(expression, base_globals, locals_)
272
+ except Exception as err:
273
+ raise NameError(
274
+ f"Could not de-stringify annotation {expression!r}"
275
+ ) from err
276
+ else:
277
+ return annotation
278
+
279
+
280
+ def eval_name_only(
281
+ name: str,
282
+ module_name: str,
283
+ *,
284
+ locals_: Optional[Mapping[str, Any]] = None,
285
+ ) -> Any:
286
+ if "." in name:
287
+ return eval_expression(name, module_name, locals_=locals_)
288
+
289
+ try:
290
+ base_globals: Dict[str, Any] = sys.modules[module_name].__dict__
291
+ except KeyError as ke:
292
+ raise NameError(
293
+ f"Module {module_name} isn't present in sys.modules; can't "
294
+ f"resolve name {name}"
295
+ ) from ke
296
+
297
+ # name only, just look in globals. eval() works perfectly fine here,
298
+ # however we are seeking to have this be faster, as this occurs for
299
+ # every Mapper[] keyword, etc. depending on configuration
300
+ try:
301
+ return base_globals[name]
302
+ except KeyError as ke:
303
+ # check in builtins as well to handle `list`, `set` or `dict`, etc.
304
+ try:
305
+ return builtins.__dict__[name]
306
+ except KeyError:
307
+ pass
308
+
309
+ raise NameError(
310
+ f"Could not locate name {name} in module {module_name}"
311
+ ) from ke
312
+
313
+
314
+ def resolve_name_to_real_class_name(name: str, module_name: str) -> str:
315
+ try:
316
+ obj = eval_name_only(name, module_name)
317
+ except NameError:
318
+ return name
319
+ else:
320
+ return getattr(obj, "__name__", name)
321
+
322
+
323
+ def is_pep593(type_: Optional[Any]) -> bool:
324
+ return type_ is not None and get_origin(type_) in _type_tuples.Annotated
325
+
326
+
327
+ def is_non_string_iterable(obj: Any) -> TypeGuard[Iterable[Any]]:
328
+ return isinstance(obj, collections_abc.Iterable) and not isinstance(
329
+ obj, (str, bytes)
330
+ )
331
+
332
+
333
+ def is_literal(type_: Any) -> bool:
334
+ return get_origin(type_) in _type_tuples.Literal
335
+
336
+
337
+ def is_newtype(type_: Optional[_AnnotationScanType]) -> TypeGuard[NewType]:
338
+ return isinstance(type_, _type_tuples.NewType)
339
+
340
+
341
+ def is_generic(type_: _AnnotationScanType) -> TypeGuard[GenericProtocol[Any]]:
342
+ return hasattr(type_, "__args__") and hasattr(type_, "__origin__")
343
+
344
+
345
+ def is_pep695(type_: _AnnotationScanType) -> TypeGuard[TypeAliasType]:
346
+ # NOTE: a generic TAT does not instance check as TypeAliasType outside of
347
+ # python 3.10. For sqlalchemy use cases it's fine to consider it a TAT
348
+ # though.
349
+ # NOTE: things seems to work also without this additional check
350
+ if is_generic(type_):
351
+ return is_pep695(type_.__origin__)
352
+ return isinstance(type_, _type_instances.TypeAliasType)
353
+
354
+
355
+ def pep695_values(type_: _AnnotationScanType) -> Set[Any]:
356
+ """Extracts the value from a TypeAliasType, recursively exploring unions
357
+ and inner TypeAliasType to flatten them into a single set.
358
+
359
+ Forward references are not evaluated, so no recursive exploration happens
360
+ into them.
361
+ """
362
+ _seen = set()
363
+
364
+ def recursive_value(inner_type):
365
+ if inner_type in _seen:
366
+ # recursion are not supported (at least it's flagged as
367
+ # an error by pyright). Just avoid infinite loop
368
+ return inner_type
369
+ _seen.add(inner_type)
370
+ if not is_pep695(inner_type):
371
+ return inner_type
372
+ value = inner_type.__value__
373
+ if not is_union(value):
374
+ return value
375
+ return [recursive_value(t) for t in value.__args__]
376
+
377
+ res = recursive_value(type_)
378
+ if isinstance(res, list):
379
+ types = set()
380
+ stack = deque(res)
381
+ while stack:
382
+ t = stack.popleft()
383
+ if isinstance(t, list):
384
+ stack.extend(t)
385
+ else:
386
+ types.add(None if t is NoneType or is_fwd_none(t) else t)
387
+ return types
388
+ else:
389
+ return {res}
390
+
391
+
392
+ @overload
393
+ def is_fwd_ref(
394
+ type_: _AnnotationScanType,
395
+ check_generic: bool = ...,
396
+ check_for_plain_string: Literal[False] = ...,
397
+ ) -> TypeGuard[ForwardRef]: ...
398
+
399
+
400
+ @overload
401
+ def is_fwd_ref(
402
+ type_: _AnnotationScanType,
403
+ check_generic: bool = ...,
404
+ check_for_plain_string: bool = ...,
405
+ ) -> TypeGuard[Union[str, ForwardRef]]: ...
406
+
407
+
408
+ def is_fwd_ref(
409
+ type_: _AnnotationScanType,
410
+ check_generic: bool = False,
411
+ check_for_plain_string: bool = False,
412
+ ) -> TypeGuard[Union[str, ForwardRef]]:
413
+ if check_for_plain_string and isinstance(type_, str):
414
+ return True
415
+ elif isinstance(type_, _type_instances.ForwardRef):
416
+ return True
417
+ elif check_generic and is_generic(type_):
418
+ return any(
419
+ is_fwd_ref(
420
+ arg, True, check_for_plain_string=check_for_plain_string
421
+ )
422
+ for arg in type_.__args__
423
+ )
424
+ else:
425
+ return False
426
+
427
+
428
+ @overload
429
+ def de_optionalize_union_types(type_: str) -> str: ...
430
+
431
+
432
+ @overload
433
+ def de_optionalize_union_types(type_: Type[Any]) -> Type[Any]: ...
434
+
435
+
436
+ @overload
437
+ def de_optionalize_union_types(type_: _MatchedOnType) -> _MatchedOnType: ...
438
+
439
+
440
+ @overload
441
+ def de_optionalize_union_types(
442
+ type_: _AnnotationScanType,
443
+ ) -> _AnnotationScanType: ...
444
+
445
+
446
+ def de_optionalize_union_types(
447
+ type_: _AnnotationScanType,
448
+ ) -> _AnnotationScanType:
449
+ """Given a type, filter out ``Union`` types that include ``NoneType``
450
+ to not include the ``NoneType``.
451
+
452
+ """
453
+
454
+ if is_fwd_ref(type_):
455
+ return _de_optionalize_fwd_ref_union_types(type_, False)
456
+
457
+ elif is_union(type_) and includes_none(type_):
458
+ typ = {
459
+ t
460
+ for t in type_.__args__
461
+ if t is not NoneType and not is_fwd_none(t)
462
+ }
463
+
464
+ return make_union_type(*typ)
465
+
466
+ else:
467
+ return type_
468
+
469
+
470
+ @overload
471
+ def _de_optionalize_fwd_ref_union_types(
472
+ type_: ForwardRef, return_has_none: Literal[True]
473
+ ) -> bool: ...
474
+
475
+
476
+ @overload
477
+ def _de_optionalize_fwd_ref_union_types(
478
+ type_: ForwardRef, return_has_none: Literal[False]
479
+ ) -> _AnnotationScanType: ...
480
+
481
+
482
+ def _de_optionalize_fwd_ref_union_types(
483
+ type_: ForwardRef, return_has_none: bool
484
+ ) -> Union[_AnnotationScanType, bool]:
485
+ """return the non-optional type for Optional[], Union[None, ...], x|None,
486
+ etc. without de-stringifying forward refs.
487
+
488
+ unfortunately this seems to require lots of hardcoded heuristics
489
+
490
+ """
491
+
492
+ annotation = type_.__forward_arg__
493
+
494
+ mm = re.match(r"^(.+?)\[(.+)\]$", annotation)
495
+ if mm:
496
+ g1 = mm.group(1).split(".")[-1]
497
+ if g1 == "Optional":
498
+ return True if return_has_none else ForwardRef(mm.group(2))
499
+ elif g1 == "Union":
500
+ if "[" in mm.group(2):
501
+ # cases like "Union[Dict[str, int], int, None]"
502
+ elements: list[str] = []
503
+ current: list[str] = []
504
+ ignore_comma = 0
505
+ for char in mm.group(2):
506
+ if char == "[":
507
+ ignore_comma += 1
508
+ elif char == "]":
509
+ ignore_comma -= 1
510
+ elif ignore_comma == 0 and char == ",":
511
+ elements.append("".join(current).strip())
512
+ current.clear()
513
+ continue
514
+ current.append(char)
515
+ else:
516
+ elements = re.split(r",\s*", mm.group(2))
517
+ parts = [ForwardRef(elem) for elem in elements if elem != "None"]
518
+ if return_has_none:
519
+ return len(elements) != len(parts)
520
+ else:
521
+ return make_union_type(*parts) if parts else Never # type: ignore[return-value] # noqa: E501
522
+ else:
523
+ return False if return_has_none else type_
524
+
525
+ pipe_tokens = re.split(r"\s*\|\s*", annotation)
526
+ has_none = "None" in pipe_tokens
527
+ if return_has_none:
528
+ return has_none
529
+ if has_none:
530
+ anno_str = "|".join(p for p in pipe_tokens if p != "None")
531
+ return ForwardRef(anno_str) if anno_str else Never # type: ignore[return-value] # noqa: E501
532
+
533
+ return type_
534
+
535
+
536
+ def make_union_type(*types: _AnnotationScanType) -> Type[Any]:
537
+ """Make a Union type."""
538
+
539
+ return Union[types] # type: ignore
540
+
541
+
542
+ def includes_none(type_: Any) -> bool:
543
+ """Returns if the type annotation ``type_`` allows ``None``.
544
+
545
+ This function supports:
546
+ * forward refs
547
+ * unions
548
+ * pep593 - Annotated
549
+ * pep695 - TypeAliasType (does not support looking into
550
+ fw reference of other pep695)
551
+ * NewType
552
+ * plain types like ``int``, ``None``, etc
553
+ """
554
+ if is_fwd_ref(type_):
555
+ return _de_optionalize_fwd_ref_union_types(type_, True)
556
+ if is_union(type_):
557
+ return any(includes_none(t) for t in get_args(type_))
558
+ if is_pep593(type_):
559
+ return includes_none(get_args(type_)[0])
560
+ if is_pep695(type_):
561
+ return any(includes_none(t) for t in pep695_values(type_))
562
+ if is_newtype(type_):
563
+ return includes_none(type_.__supertype__)
564
+ try:
565
+ return type_ in (NoneType, None) or is_fwd_none(type_)
566
+ except TypeError:
567
+ # if type_ is Column, mapped_column(), etc. the use of "in"
568
+ # resolves to ``__eq__()`` which then gives us an expression object
569
+ # that can't resolve to boolean. just catch it all via exception
570
+ return False
571
+
572
+
573
+ def is_a_type(type_: Any) -> bool:
574
+ return (
575
+ isinstance(type_, type)
576
+ or get_origin(type_) is not None
577
+ or getattr(type_, "__module__", None)
578
+ in ("typing", "typing_extensions")
579
+ or type(type_).__mro__[0].__module__ in ("typing", "typing_extensions")
580
+ )
581
+
582
+
583
+ def is_union(type_: Any) -> TypeGuard[ArgsTypeProtocol]:
584
+ return is_origin_of(type_, "Union", "UnionType")
585
+
586
+
587
+ def is_origin_of_cls(
588
+ type_: Any, class_obj: Union[Tuple[Type[Any], ...], Type[Any]]
589
+ ) -> bool:
590
+ """return True if the given type has an __origin__ that shares a base
591
+ with the given class"""
592
+
593
+ origin = get_origin(type_)
594
+ if origin is None:
595
+ return False
596
+
597
+ return isinstance(origin, type) and issubclass(origin, class_obj)
598
+
599
+
600
+ def is_origin_of(
601
+ type_: Any, *names: str, module: Optional[str] = None
602
+ ) -> bool:
603
+ """return True if the given type has an __origin__ with the given name
604
+ and optional module."""
605
+
606
+ origin = get_origin(type_)
607
+ if origin is None:
608
+ return False
609
+
610
+ return origin.__name__ in names and (
611
+ module is None or origin.__module__.startswith(module)
612
+ )
613
+
614
+
615
+ class DescriptorProto(Protocol):
616
+ def __get__(self, instance: object, owner: Any) -> Any: ...
617
+
618
+ def __set__(self, instance: Any, value: Any) -> None: ...
619
+
620
+ def __delete__(self, instance: Any) -> None: ...
621
+
622
+
623
+ _DESC = TypeVar("_DESC", bound=DescriptorProto)
624
+
625
+
626
+ class DescriptorReference(Generic[_DESC]):
627
+ """a descriptor that refers to a descriptor.
628
+
629
+ used for cases where we need to have an instance variable referring to an
630
+ object that is itself a descriptor, which typically confuses typing tools
631
+ as they don't know when they should use ``__get__`` or not when referring
632
+ to the descriptor assignment as an instance variable. See
633
+ sqlalchemy.orm.interfaces.PropComparator.prop
634
+
635
+ """
636
+
637
+ if TYPE_CHECKING:
638
+
639
+ def __get__(self, instance: object, owner: Any) -> _DESC: ...
640
+
641
+ def __set__(self, instance: Any, value: _DESC) -> None: ...
642
+
643
+ def __delete__(self, instance: Any) -> None: ...
644
+
645
+
646
+ _DESC_co = TypeVar("_DESC_co", bound=DescriptorProto, covariant=True)
647
+
648
+
649
+ class RODescriptorReference(Generic[_DESC_co]):
650
+ """a descriptor that refers to a descriptor.
651
+
652
+ same as :class:`.DescriptorReference` but is read-only, so that subclasses
653
+ can define a subtype as the generically contained element
654
+
655
+ """
656
+
657
+ if TYPE_CHECKING:
658
+
659
+ def __get__(self, instance: object, owner: Any) -> _DESC_co: ...
660
+
661
+ def __set__(self, instance: Any, value: Any) -> NoReturn: ...
662
+
663
+ def __delete__(self, instance: Any) -> NoReturn: ...
664
+
665
+
666
+ _FN = TypeVar("_FN", bound=Optional[Callable[..., Any]])
667
+
668
+
669
+ class CallableReference(Generic[_FN]):
670
+ """a descriptor that refers to a callable.
671
+
672
+ works around mypy's limitation of not allowing callables assigned
673
+ as instance variables
674
+
675
+
676
+ """
677
+
678
+ if TYPE_CHECKING:
679
+
680
+ def __get__(self, instance: object, owner: Any) -> _FN: ...
681
+
682
+ def __set__(self, instance: Any, value: _FN) -> None: ...
683
+
684
+ def __delete__(self, instance: Any) -> None: ...
685
+
686
+
687
+ class _TypingInstances:
688
+ def __getattr__(self, key: str) -> tuple[type, ...]:
689
+ types = tuple(
690
+ {
691
+ t
692
+ for t in [
693
+ getattr(typing, key, None),
694
+ getattr(typing_extensions, key, None),
695
+ ]
696
+ if t is not None
697
+ }
698
+ )
699
+ if not types:
700
+ raise AttributeError(key)
701
+ self.__dict__[key] = types
702
+ return types
703
+
704
+
705
+ _type_tuples = _TypingInstances()
706
+ if TYPE_CHECKING:
707
+ _type_instances = typing_extensions
708
+ else:
709
+ _type_instances = _type_tuples
710
+
711
+ LITERAL_TYPES = _type_tuples.Literal