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