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