SQLAlchemy 2.0.36__cp313-cp313-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 (273) hide show
  1. SQLAlchemy-2.0.36.dist-info/LICENSE +19 -0
  2. SQLAlchemy-2.0.36.dist-info/METADATA +243 -0
  3. SQLAlchemy-2.0.36.dist-info/RECORD +273 -0
  4. SQLAlchemy-2.0.36.dist-info/WHEEL +5 -0
  5. SQLAlchemy-2.0.36.dist-info/top_level.txt +1 -0
  6. sqlalchemy/__init__.py +294 -0
  7. sqlalchemy/connectors/__init__.py +18 -0
  8. sqlalchemy/connectors/aioodbc.py +174 -0
  9. sqlalchemy/connectors/asyncio.py +213 -0
  10. sqlalchemy/connectors/pyodbc.py +249 -0
  11. sqlalchemy/cyextension/__init__.py +6 -0
  12. sqlalchemy/cyextension/collections.cp313-win32.pyd +0 -0
  13. sqlalchemy/cyextension/collections.pyx +409 -0
  14. sqlalchemy/cyextension/immutabledict.cp313-win32.pyd +0 -0
  15. sqlalchemy/cyextension/immutabledict.pxd +8 -0
  16. sqlalchemy/cyextension/immutabledict.pyx +133 -0
  17. sqlalchemy/cyextension/processors.cp313-win32.pyd +0 -0
  18. sqlalchemy/cyextension/processors.pyx +68 -0
  19. sqlalchemy/cyextension/resultproxy.cp313-win32.pyd +0 -0
  20. sqlalchemy/cyextension/resultproxy.pyx +102 -0
  21. sqlalchemy/cyextension/util.cp313-win32.pyd +0 -0
  22. sqlalchemy/cyextension/util.pyx +91 -0
  23. sqlalchemy/dialects/__init__.py +61 -0
  24. sqlalchemy/dialects/_typing.py +25 -0
  25. sqlalchemy/dialects/mssql/__init__.py +88 -0
  26. sqlalchemy/dialects/mssql/aioodbc.py +64 -0
  27. sqlalchemy/dialects/mssql/base.py +4010 -0
  28. sqlalchemy/dialects/mssql/information_schema.py +254 -0
  29. sqlalchemy/dialects/mssql/json.py +133 -0
  30. sqlalchemy/dialects/mssql/provision.py +162 -0
  31. sqlalchemy/dialects/mssql/pymssql.py +126 -0
  32. sqlalchemy/dialects/mssql/pyodbc.py +745 -0
  33. sqlalchemy/dialects/mysql/__init__.py +101 -0
  34. sqlalchemy/dialects/mysql/aiomysql.py +333 -0
  35. sqlalchemy/dialects/mysql/asyncmy.py +337 -0
  36. sqlalchemy/dialects/mysql/base.py +3494 -0
  37. sqlalchemy/dialects/mysql/cymysql.py +84 -0
  38. sqlalchemy/dialects/mysql/dml.py +219 -0
  39. sqlalchemy/dialects/mysql/enumerated.py +244 -0
  40. sqlalchemy/dialects/mysql/expression.py +141 -0
  41. sqlalchemy/dialects/mysql/json.py +81 -0
  42. sqlalchemy/dialects/mysql/mariadb.py +32 -0
  43. sqlalchemy/dialects/mysql/mariadbconnector.py +277 -0
  44. sqlalchemy/dialects/mysql/mysqlconnector.py +180 -0
  45. sqlalchemy/dialects/mysql/mysqldb.py +303 -0
  46. sqlalchemy/dialects/mysql/provision.py +110 -0
  47. sqlalchemy/dialects/mysql/pymysql.py +137 -0
  48. sqlalchemy/dialects/mysql/pyodbc.py +138 -0
  49. sqlalchemy/dialects/mysql/reflection.py +677 -0
  50. sqlalchemy/dialects/mysql/reserved_words.py +571 -0
  51. sqlalchemy/dialects/mysql/types.py +774 -0
  52. sqlalchemy/dialects/oracle/__init__.py +67 -0
  53. sqlalchemy/dialects/oracle/base.py +3271 -0
  54. sqlalchemy/dialects/oracle/cx_oracle.py +1483 -0
  55. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  56. sqlalchemy/dialects/oracle/oracledb.py +431 -0
  57. sqlalchemy/dialects/oracle/provision.py +220 -0
  58. sqlalchemy/dialects/oracle/types.py +287 -0
  59. sqlalchemy/dialects/postgresql/__init__.py +167 -0
  60. sqlalchemy/dialects/postgresql/_psycopg_common.py +187 -0
  61. sqlalchemy/dialects/postgresql/array.py +425 -0
  62. sqlalchemy/dialects/postgresql/asyncpg.py +1274 -0
  63. sqlalchemy/dialects/postgresql/base.py +5008 -0
  64. sqlalchemy/dialects/postgresql/dml.py +310 -0
  65. sqlalchemy/dialects/postgresql/ext.py +496 -0
  66. sqlalchemy/dialects/postgresql/hstore.py +397 -0
  67. sqlalchemy/dialects/postgresql/json.py +333 -0
  68. sqlalchemy/dialects/postgresql/named_types.py +509 -0
  69. sqlalchemy/dialects/postgresql/operators.py +129 -0
  70. sqlalchemy/dialects/postgresql/pg8000.py +662 -0
  71. sqlalchemy/dialects/postgresql/pg_catalog.py +300 -0
  72. sqlalchemy/dialects/postgresql/provision.py +175 -0
  73. sqlalchemy/dialects/postgresql/psycopg.py +772 -0
  74. sqlalchemy/dialects/postgresql/psycopg2.py +886 -0
  75. sqlalchemy/dialects/postgresql/psycopg2cffi.py +61 -0
  76. sqlalchemy/dialects/postgresql/ranges.py +1029 -0
  77. sqlalchemy/dialects/postgresql/types.py +303 -0
  78. sqlalchemy/dialects/sqlite/__init__.py +57 -0
  79. sqlalchemy/dialects/sqlite/aiosqlite.py +396 -0
  80. sqlalchemy/dialects/sqlite/base.py +2805 -0
  81. sqlalchemy/dialects/sqlite/dml.py +240 -0
  82. sqlalchemy/dialects/sqlite/json.py +92 -0
  83. sqlalchemy/dialects/sqlite/provision.py +198 -0
  84. sqlalchemy/dialects/sqlite/pysqlcipher.py +155 -0
  85. sqlalchemy/dialects/sqlite/pysqlite.py +756 -0
  86. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  87. sqlalchemy/engine/__init__.py +62 -0
  88. sqlalchemy/engine/_py_processors.py +136 -0
  89. sqlalchemy/engine/_py_row.py +128 -0
  90. sqlalchemy/engine/_py_util.py +74 -0
  91. sqlalchemy/engine/base.py +3375 -0
  92. sqlalchemy/engine/characteristics.py +155 -0
  93. sqlalchemy/engine/create.py +875 -0
  94. sqlalchemy/engine/cursor.py +2181 -0
  95. sqlalchemy/engine/default.py +2365 -0
  96. sqlalchemy/engine/events.py +951 -0
  97. sqlalchemy/engine/interfaces.py +3403 -0
  98. sqlalchemy/engine/mock.py +131 -0
  99. sqlalchemy/engine/processors.py +61 -0
  100. sqlalchemy/engine/reflection.py +2098 -0
  101. sqlalchemy/engine/result.py +2382 -0
  102. sqlalchemy/engine/row.py +401 -0
  103. sqlalchemy/engine/strategies.py +19 -0
  104. sqlalchemy/engine/url.py +910 -0
  105. sqlalchemy/engine/util.py +167 -0
  106. sqlalchemy/event/__init__.py +25 -0
  107. sqlalchemy/event/api.py +225 -0
  108. sqlalchemy/event/attr.py +655 -0
  109. sqlalchemy/event/base.py +470 -0
  110. sqlalchemy/event/legacy.py +246 -0
  111. sqlalchemy/event/registry.py +386 -0
  112. sqlalchemy/events.py +17 -0
  113. sqlalchemy/exc.py +830 -0
  114. sqlalchemy/ext/__init__.py +11 -0
  115. sqlalchemy/ext/associationproxy.py +2013 -0
  116. sqlalchemy/ext/asyncio/__init__.py +25 -0
  117. sqlalchemy/ext/asyncio/base.py +279 -0
  118. sqlalchemy/ext/asyncio/engine.py +1466 -0
  119. sqlalchemy/ext/asyncio/exc.py +21 -0
  120. sqlalchemy/ext/asyncio/result.py +961 -0
  121. sqlalchemy/ext/asyncio/scoping.py +1614 -0
  122. sqlalchemy/ext/asyncio/session.py +1936 -0
  123. sqlalchemy/ext/automap.py +1691 -0
  124. sqlalchemy/ext/baked.py +574 -0
  125. sqlalchemy/ext/compiler.py +570 -0
  126. sqlalchemy/ext/declarative/__init__.py +65 -0
  127. sqlalchemy/ext/declarative/extensions.py +548 -0
  128. sqlalchemy/ext/horizontal_shard.py +481 -0
  129. sqlalchemy/ext/hybrid.py +1514 -0
  130. sqlalchemy/ext/indexable.py +341 -0
  131. sqlalchemy/ext/instrumentation.py +450 -0
  132. sqlalchemy/ext/mutable.py +1073 -0
  133. sqlalchemy/ext/mypy/__init__.py +6 -0
  134. sqlalchemy/ext/mypy/apply.py +320 -0
  135. sqlalchemy/ext/mypy/decl_class.py +515 -0
  136. sqlalchemy/ext/mypy/infer.py +590 -0
  137. sqlalchemy/ext/mypy/names.py +335 -0
  138. sqlalchemy/ext/mypy/plugin.py +303 -0
  139. sqlalchemy/ext/mypy/util.py +357 -0
  140. sqlalchemy/ext/orderinglist.py +416 -0
  141. sqlalchemy/ext/serializer.py +181 -0
  142. sqlalchemy/future/__init__.py +16 -0
  143. sqlalchemy/future/engine.py +15 -0
  144. sqlalchemy/inspection.py +174 -0
  145. sqlalchemy/log.py +288 -0
  146. sqlalchemy/orm/__init__.py +170 -0
  147. sqlalchemy/orm/_orm_constructors.py +2571 -0
  148. sqlalchemy/orm/_typing.py +179 -0
  149. sqlalchemy/orm/attributes.py +2835 -0
  150. sqlalchemy/orm/base.py +973 -0
  151. sqlalchemy/orm/bulk_persistence.py +2123 -0
  152. sqlalchemy/orm/clsregistry.py +571 -0
  153. sqlalchemy/orm/collections.py +1620 -0
  154. sqlalchemy/orm/context.py +3268 -0
  155. sqlalchemy/orm/decl_api.py +1883 -0
  156. sqlalchemy/orm/decl_base.py +2190 -0
  157. sqlalchemy/orm/dependency.py +1304 -0
  158. sqlalchemy/orm/descriptor_props.py +1076 -0
  159. sqlalchemy/orm/dynamic.py +300 -0
  160. sqlalchemy/orm/evaluator.py +379 -0
  161. sqlalchemy/orm/events.py +3261 -0
  162. sqlalchemy/orm/exc.py +228 -0
  163. sqlalchemy/orm/identity.py +302 -0
  164. sqlalchemy/orm/instrumentation.py +754 -0
  165. sqlalchemy/orm/interfaces.py +1474 -0
  166. sqlalchemy/orm/loading.py +1682 -0
  167. sqlalchemy/orm/mapped_collection.py +557 -0
  168. sqlalchemy/orm/mapper.py +4432 -0
  169. sqlalchemy/orm/path_registry.py +811 -0
  170. sqlalchemy/orm/persistence.py +1782 -0
  171. sqlalchemy/orm/properties.py +886 -0
  172. sqlalchemy/orm/query.py +3396 -0
  173. sqlalchemy/orm/relationships.py +3500 -0
  174. sqlalchemy/orm/scoping.py +2165 -0
  175. sqlalchemy/orm/session.py +5301 -0
  176. sqlalchemy/orm/state.py +1143 -0
  177. sqlalchemy/orm/state_changes.py +198 -0
  178. sqlalchemy/orm/strategies.py +3473 -0
  179. sqlalchemy/orm/strategy_options.py +2569 -0
  180. sqlalchemy/orm/sync.py +164 -0
  181. sqlalchemy/orm/unitofwork.py +796 -0
  182. sqlalchemy/orm/util.py +2424 -0
  183. sqlalchemy/orm/writeonly.py +678 -0
  184. sqlalchemy/pool/__init__.py +44 -0
  185. sqlalchemy/pool/base.py +1515 -0
  186. sqlalchemy/pool/events.py +370 -0
  187. sqlalchemy/pool/impl.py +581 -0
  188. sqlalchemy/py.typed +0 -0
  189. sqlalchemy/schema.py +70 -0
  190. sqlalchemy/sql/__init__.py +145 -0
  191. sqlalchemy/sql/_dml_constructors.py +140 -0
  192. sqlalchemy/sql/_elements_constructors.py +1850 -0
  193. sqlalchemy/sql/_orm_types.py +20 -0
  194. sqlalchemy/sql/_py_util.py +75 -0
  195. sqlalchemy/sql/_selectable_constructors.py +635 -0
  196. sqlalchemy/sql/_typing.py +460 -0
  197. sqlalchemy/sql/annotation.py +585 -0
  198. sqlalchemy/sql/base.py +2185 -0
  199. sqlalchemy/sql/cache_key.py +1057 -0
  200. sqlalchemy/sql/coercions.py +1405 -0
  201. sqlalchemy/sql/compiler.py +7818 -0
  202. sqlalchemy/sql/crud.py +1669 -0
  203. sqlalchemy/sql/ddl.py +1378 -0
  204. sqlalchemy/sql/default_comparator.py +552 -0
  205. sqlalchemy/sql/dml.py +1817 -0
  206. sqlalchemy/sql/elements.py +5499 -0
  207. sqlalchemy/sql/events.py +455 -0
  208. sqlalchemy/sql/expression.py +162 -0
  209. sqlalchemy/sql/functions.py +2055 -0
  210. sqlalchemy/sql/lambdas.py +1449 -0
  211. sqlalchemy/sql/naming.py +212 -0
  212. sqlalchemy/sql/operators.py +2579 -0
  213. sqlalchemy/sql/roles.py +323 -0
  214. sqlalchemy/sql/schema.py +6158 -0
  215. sqlalchemy/sql/selectable.py +7004 -0
  216. sqlalchemy/sql/sqltypes.py +3827 -0
  217. sqlalchemy/sql/traversals.py +1024 -0
  218. sqlalchemy/sql/type_api.py +2339 -0
  219. sqlalchemy/sql/util.py +1486 -0
  220. sqlalchemy/sql/visitors.py +1165 -0
  221. sqlalchemy/testing/__init__.py +96 -0
  222. sqlalchemy/testing/assertions.py +989 -0
  223. sqlalchemy/testing/assertsql.py +516 -0
  224. sqlalchemy/testing/asyncio.py +135 -0
  225. sqlalchemy/testing/config.py +427 -0
  226. sqlalchemy/testing/engines.py +472 -0
  227. sqlalchemy/testing/entities.py +117 -0
  228. sqlalchemy/testing/exclusions.py +435 -0
  229. sqlalchemy/testing/fixtures/__init__.py +28 -0
  230. sqlalchemy/testing/fixtures/base.py +366 -0
  231. sqlalchemy/testing/fixtures/mypy.py +312 -0
  232. sqlalchemy/testing/fixtures/orm.py +227 -0
  233. sqlalchemy/testing/fixtures/sql.py +503 -0
  234. sqlalchemy/testing/pickleable.py +155 -0
  235. sqlalchemy/testing/plugin/__init__.py +6 -0
  236. sqlalchemy/testing/plugin/bootstrap.py +51 -0
  237. sqlalchemy/testing/plugin/plugin_base.py +779 -0
  238. sqlalchemy/testing/plugin/pytestplugin.py +868 -0
  239. sqlalchemy/testing/profiling.py +324 -0
  240. sqlalchemy/testing/provision.py +496 -0
  241. sqlalchemy/testing/requirements.py +1818 -0
  242. sqlalchemy/testing/schema.py +224 -0
  243. sqlalchemy/testing/suite/__init__.py +19 -0
  244. sqlalchemy/testing/suite/test_cte.py +211 -0
  245. sqlalchemy/testing/suite/test_ddl.py +389 -0
  246. sqlalchemy/testing/suite/test_deprecations.py +153 -0
  247. sqlalchemy/testing/suite/test_dialect.py +740 -0
  248. sqlalchemy/testing/suite/test_insert.py +630 -0
  249. sqlalchemy/testing/suite/test_reflection.py +3225 -0
  250. sqlalchemy/testing/suite/test_results.py +502 -0
  251. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  252. sqlalchemy/testing/suite/test_select.py +1999 -0
  253. sqlalchemy/testing/suite/test_sequence.py +317 -0
  254. sqlalchemy/testing/suite/test_types.py +2141 -0
  255. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  256. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  257. sqlalchemy/testing/util.py +537 -0
  258. sqlalchemy/testing/warnings.py +52 -0
  259. sqlalchemy/types.py +76 -0
  260. sqlalchemy/util/__init__.py +160 -0
  261. sqlalchemy/util/_collections.py +715 -0
  262. sqlalchemy/util/_concurrency_py3k.py +288 -0
  263. sqlalchemy/util/_has_cy.py +40 -0
  264. sqlalchemy/util/_py_collections.py +541 -0
  265. sqlalchemy/util/compat.py +301 -0
  266. sqlalchemy/util/concurrency.py +108 -0
  267. sqlalchemy/util/deprecations.py +401 -0
  268. sqlalchemy/util/langhelpers.py +2218 -0
  269. sqlalchemy/util/preloaded.py +150 -0
  270. sqlalchemy/util/queue.py +322 -0
  271. sqlalchemy/util/tool_support.py +201 -0
  272. sqlalchemy/util/topological.py +120 -0
  273. sqlalchemy/util/typing.py +629 -0
@@ -0,0 +1,2218 @@
1
+ # util/langhelpers.py
2
+ # Copyright (C) 2005-2024 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
+ """Routines to help with the creation, loading and introspection of
10
+ modules, classes, hierarchies, attributes, functions, and methods.
11
+
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import collections
16
+ import enum
17
+ from functools import update_wrapper
18
+ import inspect
19
+ import itertools
20
+ import operator
21
+ import re
22
+ import sys
23
+ import textwrap
24
+ import threading
25
+ import types
26
+ from types import CodeType
27
+ from typing import Any
28
+ from typing import Callable
29
+ from typing import cast
30
+ from typing import Dict
31
+ from typing import FrozenSet
32
+ from typing import Generic
33
+ from typing import Iterator
34
+ from typing import List
35
+ from typing import Mapping
36
+ from typing import NoReturn
37
+ from typing import Optional
38
+ from typing import overload
39
+ from typing import Sequence
40
+ from typing import Set
41
+ from typing import Tuple
42
+ from typing import Type
43
+ from typing import TYPE_CHECKING
44
+ from typing import TypeVar
45
+ from typing import Union
46
+ import warnings
47
+
48
+ from . import _collections
49
+ from . import compat
50
+ from ._has_cy import HAS_CYEXTENSION
51
+ from .typing import Literal
52
+ from .. import exc
53
+
54
+ _T = TypeVar("_T")
55
+ _T_co = TypeVar("_T_co", covariant=True)
56
+ _F = TypeVar("_F", bound=Callable[..., Any])
57
+ _MP = TypeVar("_MP", bound="memoized_property[Any]")
58
+ _MA = TypeVar("_MA", bound="HasMemoized.memoized_attribute[Any]")
59
+ _HP = TypeVar("_HP", bound="hybridproperty[Any]")
60
+ _HM = TypeVar("_HM", bound="hybridmethod[Any]")
61
+
62
+
63
+ if compat.py310:
64
+
65
+ def get_annotations(obj: Any) -> Mapping[str, Any]:
66
+ return inspect.get_annotations(obj)
67
+
68
+ else:
69
+
70
+ def get_annotations(obj: Any) -> Mapping[str, Any]:
71
+ # it's been observed that cls.__annotations__ can be non present.
72
+ # it's not clear what causes this, running under tox py37/38 it
73
+ # happens, running straight pytest it doesnt
74
+
75
+ # https://docs.python.org/3/howto/annotations.html#annotations-howto
76
+ if isinstance(obj, type):
77
+ ann = obj.__dict__.get("__annotations__", None)
78
+ else:
79
+ ann = getattr(obj, "__annotations__", None)
80
+
81
+ if ann is None:
82
+ return _collections.EMPTY_DICT
83
+ else:
84
+ return cast("Mapping[str, Any]", ann)
85
+
86
+
87
+ def md5_hex(x: Any) -> str:
88
+ x = x.encode("utf-8")
89
+ m = compat.md5_not_for_security()
90
+ m.update(x)
91
+ return cast(str, m.hexdigest())
92
+
93
+
94
+ class safe_reraise:
95
+ """Reraise an exception after invoking some
96
+ handler code.
97
+
98
+ Stores the existing exception info before
99
+ invoking so that it is maintained across a potential
100
+ coroutine context switch.
101
+
102
+ e.g.::
103
+
104
+ try:
105
+ sess.commit()
106
+ except:
107
+ with safe_reraise():
108
+ sess.rollback()
109
+
110
+ TODO: we should at some point evaluate current behaviors in this regard
111
+ based on current greenlet, gevent/eventlet implementations in Python 3, and
112
+ also see the degree to which our own asyncio (based on greenlet also) is
113
+ impacted by this. .rollback() will cause IO / context switch to occur in
114
+ all these scenarios; what happens to the exception context from an
115
+ "except:" block if we don't explicitly store it? Original issue was #2703.
116
+
117
+ """
118
+
119
+ __slots__ = ("_exc_info",)
120
+
121
+ _exc_info: Union[
122
+ None,
123
+ Tuple[
124
+ Type[BaseException],
125
+ BaseException,
126
+ types.TracebackType,
127
+ ],
128
+ Tuple[None, None, None],
129
+ ]
130
+
131
+ def __enter__(self) -> None:
132
+ self._exc_info = sys.exc_info()
133
+
134
+ def __exit__(
135
+ self,
136
+ type_: Optional[Type[BaseException]],
137
+ value: Optional[BaseException],
138
+ traceback: Optional[types.TracebackType],
139
+ ) -> NoReturn:
140
+ assert self._exc_info is not None
141
+ # see #2703 for notes
142
+ if type_ is None:
143
+ exc_type, exc_value, exc_tb = self._exc_info
144
+ assert exc_value is not None
145
+ self._exc_info = None # remove potential circular references
146
+ raise exc_value.with_traceback(exc_tb)
147
+ else:
148
+ self._exc_info = None # remove potential circular references
149
+ assert value is not None
150
+ raise value.with_traceback(traceback)
151
+
152
+
153
+ def walk_subclasses(cls: Type[_T]) -> Iterator[Type[_T]]:
154
+ seen: Set[Any] = set()
155
+
156
+ stack = [cls]
157
+ while stack:
158
+ cls = stack.pop()
159
+ if cls in seen:
160
+ continue
161
+ else:
162
+ seen.add(cls)
163
+ stack.extend(cls.__subclasses__())
164
+ yield cls
165
+
166
+
167
+ def string_or_unprintable(element: Any) -> str:
168
+ if isinstance(element, str):
169
+ return element
170
+ else:
171
+ try:
172
+ return str(element)
173
+ except Exception:
174
+ return "unprintable element %r" % element
175
+
176
+
177
+ def clsname_as_plain_name(
178
+ cls: Type[Any], use_name: Optional[str] = None
179
+ ) -> str:
180
+ name = use_name or cls.__name__
181
+ return " ".join(n.lower() for n in re.findall(r"([A-Z][a-z]+|SQL)", name))
182
+
183
+
184
+ def method_is_overridden(
185
+ instance_or_cls: Union[Type[Any], object],
186
+ against_method: Callable[..., Any],
187
+ ) -> bool:
188
+ """Return True if the two class methods don't match."""
189
+
190
+ if not isinstance(instance_or_cls, type):
191
+ current_cls = instance_or_cls.__class__
192
+ else:
193
+ current_cls = instance_or_cls
194
+
195
+ method_name = against_method.__name__
196
+
197
+ current_method: types.MethodType = getattr(current_cls, method_name)
198
+
199
+ return current_method != against_method
200
+
201
+
202
+ def decode_slice(slc: slice) -> Tuple[Any, ...]:
203
+ """decode a slice object as sent to __getitem__.
204
+
205
+ takes into account the 2.5 __index__() method, basically.
206
+
207
+ """
208
+ ret: List[Any] = []
209
+ for x in slc.start, slc.stop, slc.step:
210
+ if hasattr(x, "__index__"):
211
+ x = x.__index__()
212
+ ret.append(x)
213
+ return tuple(ret)
214
+
215
+
216
+ def _unique_symbols(used: Sequence[str], *bases: str) -> Iterator[str]:
217
+ used_set = set(used)
218
+ for base in bases:
219
+ pool = itertools.chain(
220
+ (base,),
221
+ map(lambda i: base + str(i), range(1000)),
222
+ )
223
+ for sym in pool:
224
+ if sym not in used_set:
225
+ used_set.add(sym)
226
+ yield sym
227
+ break
228
+ else:
229
+ raise NameError("exhausted namespace for symbol base %s" % base)
230
+
231
+
232
+ def map_bits(fn: Callable[[int], Any], n: int) -> Iterator[Any]:
233
+ """Call the given function given each nonzero bit from n."""
234
+
235
+ while n:
236
+ b = n & (~n + 1)
237
+ yield fn(b)
238
+ n ^= b
239
+
240
+
241
+ _Fn = TypeVar("_Fn", bound="Callable[..., Any]")
242
+
243
+ # this seems to be in flux in recent mypy versions
244
+
245
+
246
+ def decorator(target: Callable[..., Any]) -> Callable[[_Fn], _Fn]:
247
+ """A signature-matching decorator factory."""
248
+
249
+ def decorate(fn: _Fn) -> _Fn:
250
+ if not inspect.isfunction(fn) and not inspect.ismethod(fn):
251
+ raise Exception("not a decoratable function")
252
+
253
+ spec = compat.inspect_getfullargspec(fn)
254
+ env: Dict[str, Any] = {}
255
+
256
+ spec = _update_argspec_defaults_into_env(spec, env)
257
+
258
+ names = (
259
+ tuple(cast("Tuple[str, ...]", spec[0]))
260
+ + cast("Tuple[str, ...]", spec[1:3])
261
+ + (fn.__name__,)
262
+ )
263
+ targ_name, fn_name = _unique_symbols(names, "target", "fn")
264
+
265
+ metadata: Dict[str, Optional[str]] = dict(target=targ_name, fn=fn_name)
266
+ metadata.update(format_argspec_plus(spec, grouped=False))
267
+ metadata["name"] = fn.__name__
268
+
269
+ if inspect.iscoroutinefunction(fn):
270
+ metadata["prefix"] = "async "
271
+ metadata["target_prefix"] = "await "
272
+ else:
273
+ metadata["prefix"] = ""
274
+ metadata["target_prefix"] = ""
275
+
276
+ # look for __ positional arguments. This is a convention in
277
+ # SQLAlchemy that arguments should be passed positionally
278
+ # rather than as keyword
279
+ # arguments. note that apply_pos doesn't currently work in all cases
280
+ # such as when a kw-only indicator "*" is present, which is why
281
+ # we limit the use of this to just that case we can detect. As we add
282
+ # more kinds of methods that use @decorator, things may have to
283
+ # be further improved in this area
284
+ if "__" in repr(spec[0]):
285
+ code = (
286
+ """\
287
+ %(prefix)sdef %(name)s%(grouped_args)s:
288
+ return %(target_prefix)s%(target)s(%(fn)s, %(apply_pos)s)
289
+ """
290
+ % metadata
291
+ )
292
+ else:
293
+ code = (
294
+ """\
295
+ %(prefix)sdef %(name)s%(grouped_args)s:
296
+ return %(target_prefix)s%(target)s(%(fn)s, %(apply_kw)s)
297
+ """
298
+ % metadata
299
+ )
300
+
301
+ mod = sys.modules[fn.__module__]
302
+ env.update(vars(mod))
303
+ env.update({targ_name: target, fn_name: fn, "__name__": fn.__module__})
304
+
305
+ decorated = cast(
306
+ types.FunctionType,
307
+ _exec_code_in_env(code, env, fn.__name__),
308
+ )
309
+ decorated.__defaults__ = getattr(fn, "__func__", fn).__defaults__
310
+
311
+ decorated.__wrapped__ = fn # type: ignore[attr-defined]
312
+ return update_wrapper(decorated, fn) # type: ignore[return-value]
313
+
314
+ return update_wrapper(decorate, target) # type: ignore[return-value]
315
+
316
+
317
+ def _update_argspec_defaults_into_env(spec, env):
318
+ """given a FullArgSpec, convert defaults to be symbol names in an env."""
319
+
320
+ if spec.defaults:
321
+ new_defaults = []
322
+ i = 0
323
+ for arg in spec.defaults:
324
+ if type(arg).__module__ not in ("builtins", "__builtin__"):
325
+ name = "x%d" % i
326
+ env[name] = arg
327
+ new_defaults.append(name)
328
+ i += 1
329
+ else:
330
+ new_defaults.append(arg)
331
+ elem = list(spec)
332
+ elem[3] = tuple(new_defaults)
333
+ return compat.FullArgSpec(*elem)
334
+ else:
335
+ return spec
336
+
337
+
338
+ def _exec_code_in_env(
339
+ code: Union[str, types.CodeType], env: Dict[str, Any], fn_name: str
340
+ ) -> Callable[..., Any]:
341
+ exec(code, env)
342
+ return env[fn_name] # type: ignore[no-any-return]
343
+
344
+
345
+ _PF = TypeVar("_PF")
346
+ _TE = TypeVar("_TE")
347
+
348
+
349
+ class PluginLoader:
350
+ def __init__(
351
+ self, group: str, auto_fn: Optional[Callable[..., Any]] = None
352
+ ):
353
+ self.group = group
354
+ self.impls: Dict[str, Any] = {}
355
+ self.auto_fn = auto_fn
356
+
357
+ def clear(self):
358
+ self.impls.clear()
359
+
360
+ def load(self, name: str) -> Any:
361
+ if name in self.impls:
362
+ return self.impls[name]()
363
+
364
+ if self.auto_fn:
365
+ loader = self.auto_fn(name)
366
+ if loader:
367
+ self.impls[name] = loader
368
+ return loader()
369
+
370
+ for impl in compat.importlib_metadata_get(self.group):
371
+ if impl.name == name:
372
+ self.impls[name] = impl.load
373
+ return impl.load()
374
+
375
+ raise exc.NoSuchModuleError(
376
+ "Can't load plugin: %s:%s" % (self.group, name)
377
+ )
378
+
379
+ def register(self, name: str, modulepath: str, objname: str) -> None:
380
+ def load():
381
+ mod = __import__(modulepath)
382
+ for token in modulepath.split(".")[1:]:
383
+ mod = getattr(mod, token)
384
+ return getattr(mod, objname)
385
+
386
+ self.impls[name] = load
387
+
388
+
389
+ def _inspect_func_args(fn):
390
+ try:
391
+ co_varkeywords = inspect.CO_VARKEYWORDS
392
+ except AttributeError:
393
+ # https://docs.python.org/3/library/inspect.html
394
+ # The flags are specific to CPython, and may not be defined in other
395
+ # Python implementations. Furthermore, the flags are an implementation
396
+ # detail, and can be removed or deprecated in future Python releases.
397
+ spec = compat.inspect_getfullargspec(fn)
398
+ return spec[0], bool(spec[2])
399
+ else:
400
+ # use fn.__code__ plus flags to reduce method call overhead
401
+ co = fn.__code__
402
+ nargs = co.co_argcount
403
+ return (
404
+ list(co.co_varnames[:nargs]),
405
+ bool(co.co_flags & co_varkeywords),
406
+ )
407
+
408
+
409
+ @overload
410
+ def get_cls_kwargs(
411
+ cls: type,
412
+ *,
413
+ _set: Optional[Set[str]] = None,
414
+ raiseerr: Literal[True] = ...,
415
+ ) -> Set[str]: ...
416
+
417
+
418
+ @overload
419
+ def get_cls_kwargs(
420
+ cls: type, *, _set: Optional[Set[str]] = None, raiseerr: bool = False
421
+ ) -> Optional[Set[str]]: ...
422
+
423
+
424
+ def get_cls_kwargs(
425
+ cls: type, *, _set: Optional[Set[str]] = None, raiseerr: bool = False
426
+ ) -> Optional[Set[str]]:
427
+ r"""Return the full set of inherited kwargs for the given `cls`.
428
+
429
+ Probes a class's __init__ method, collecting all named arguments. If the
430
+ __init__ defines a \**kwargs catch-all, then the constructor is presumed
431
+ to pass along unrecognized keywords to its base classes, and the
432
+ collection process is repeated recursively on each of the bases.
433
+
434
+ Uses a subset of inspect.getfullargspec() to cut down on method overhead,
435
+ as this is used within the Core typing system to create copies of type
436
+ objects which is a performance-sensitive operation.
437
+
438
+ No anonymous tuple arguments please !
439
+
440
+ """
441
+ toplevel = _set is None
442
+ if toplevel:
443
+ _set = set()
444
+ assert _set is not None
445
+
446
+ ctr = cls.__dict__.get("__init__", False)
447
+
448
+ has_init = (
449
+ ctr
450
+ and isinstance(ctr, types.FunctionType)
451
+ and isinstance(ctr.__code__, types.CodeType)
452
+ )
453
+
454
+ if has_init:
455
+ names, has_kw = _inspect_func_args(ctr)
456
+ _set.update(names)
457
+
458
+ if not has_kw and not toplevel:
459
+ if raiseerr:
460
+ raise TypeError(
461
+ f"given cls {cls} doesn't have an __init__ method"
462
+ )
463
+ else:
464
+ return None
465
+ else:
466
+ has_kw = False
467
+
468
+ if not has_init or has_kw:
469
+ for c in cls.__bases__:
470
+ if get_cls_kwargs(c, _set=_set) is None:
471
+ break
472
+
473
+ _set.discard("self")
474
+ return _set
475
+
476
+
477
+ def get_func_kwargs(func: Callable[..., Any]) -> List[str]:
478
+ """Return the set of legal kwargs for the given `func`.
479
+
480
+ Uses getargspec so is safe to call for methods, functions,
481
+ etc.
482
+
483
+ """
484
+
485
+ return compat.inspect_getfullargspec(func)[0]
486
+
487
+
488
+ def get_callable_argspec(
489
+ fn: Callable[..., Any], no_self: bool = False, _is_init: bool = False
490
+ ) -> compat.FullArgSpec:
491
+ """Return the argument signature for any callable.
492
+
493
+ All pure-Python callables are accepted, including
494
+ functions, methods, classes, objects with __call__;
495
+ builtins and other edge cases like functools.partial() objects
496
+ raise a TypeError.
497
+
498
+ """
499
+ if inspect.isbuiltin(fn):
500
+ raise TypeError("Can't inspect builtin: %s" % fn)
501
+ elif inspect.isfunction(fn):
502
+ if _is_init and no_self:
503
+ spec = compat.inspect_getfullargspec(fn)
504
+ return compat.FullArgSpec(
505
+ spec.args[1:],
506
+ spec.varargs,
507
+ spec.varkw,
508
+ spec.defaults,
509
+ spec.kwonlyargs,
510
+ spec.kwonlydefaults,
511
+ spec.annotations,
512
+ )
513
+ else:
514
+ return compat.inspect_getfullargspec(fn)
515
+ elif inspect.ismethod(fn):
516
+ if no_self and (_is_init or fn.__self__):
517
+ spec = compat.inspect_getfullargspec(fn.__func__)
518
+ return compat.FullArgSpec(
519
+ spec.args[1:],
520
+ spec.varargs,
521
+ spec.varkw,
522
+ spec.defaults,
523
+ spec.kwonlyargs,
524
+ spec.kwonlydefaults,
525
+ spec.annotations,
526
+ )
527
+ else:
528
+ return compat.inspect_getfullargspec(fn.__func__)
529
+ elif inspect.isclass(fn):
530
+ return get_callable_argspec(
531
+ fn.__init__, no_self=no_self, _is_init=True
532
+ )
533
+ elif hasattr(fn, "__func__"):
534
+ return compat.inspect_getfullargspec(fn.__func__)
535
+ elif hasattr(fn, "__call__"):
536
+ if inspect.ismethod(fn.__call__):
537
+ return get_callable_argspec(fn.__call__, no_self=no_self)
538
+ else:
539
+ raise TypeError("Can't inspect callable: %s" % fn)
540
+ else:
541
+ raise TypeError("Can't inspect callable: %s" % fn)
542
+
543
+
544
+ def format_argspec_plus(
545
+ fn: Union[Callable[..., Any], compat.FullArgSpec], grouped: bool = True
546
+ ) -> Dict[str, Optional[str]]:
547
+ """Returns a dictionary of formatted, introspected function arguments.
548
+
549
+ A enhanced variant of inspect.formatargspec to support code generation.
550
+
551
+ fn
552
+ An inspectable callable or tuple of inspect getargspec() results.
553
+ grouped
554
+ Defaults to True; include (parens, around, argument) lists
555
+
556
+ Returns:
557
+
558
+ args
559
+ Full inspect.formatargspec for fn
560
+ self_arg
561
+ The name of the first positional argument, varargs[0], or None
562
+ if the function defines no positional arguments.
563
+ apply_pos
564
+ args, re-written in calling rather than receiving syntax. Arguments are
565
+ passed positionally.
566
+ apply_kw
567
+ Like apply_pos, except keyword-ish args are passed as keywords.
568
+ apply_pos_proxied
569
+ Like apply_pos but omits the self/cls argument
570
+
571
+ Example::
572
+
573
+ >>> format_argspec_plus(lambda self, a, b, c=3, **d: 123)
574
+ {'grouped_args': '(self, a, b, c=3, **d)',
575
+ 'self_arg': 'self',
576
+ 'apply_kw': '(self, a, b, c=c, **d)',
577
+ 'apply_pos': '(self, a, b, c, **d)'}
578
+
579
+ """
580
+ if callable(fn):
581
+ spec = compat.inspect_getfullargspec(fn)
582
+ else:
583
+ spec = fn
584
+
585
+ args = compat.inspect_formatargspec(*spec)
586
+
587
+ apply_pos = compat.inspect_formatargspec(
588
+ spec[0], spec[1], spec[2], None, spec[4]
589
+ )
590
+
591
+ if spec[0]:
592
+ self_arg = spec[0][0]
593
+
594
+ apply_pos_proxied = compat.inspect_formatargspec(
595
+ spec[0][1:], spec[1], spec[2], None, spec[4]
596
+ )
597
+
598
+ elif spec[1]:
599
+ # I'm not sure what this is
600
+ self_arg = "%s[0]" % spec[1]
601
+
602
+ apply_pos_proxied = apply_pos
603
+ else:
604
+ self_arg = None
605
+ apply_pos_proxied = apply_pos
606
+
607
+ num_defaults = 0
608
+ if spec[3]:
609
+ num_defaults += len(cast(Tuple[Any], spec[3]))
610
+ if spec[4]:
611
+ num_defaults += len(spec[4])
612
+
613
+ name_args = spec[0] + spec[4]
614
+
615
+ defaulted_vals: Union[List[str], Tuple[()]]
616
+
617
+ if num_defaults:
618
+ defaulted_vals = name_args[0 - num_defaults :]
619
+ else:
620
+ defaulted_vals = ()
621
+
622
+ apply_kw = compat.inspect_formatargspec(
623
+ name_args,
624
+ spec[1],
625
+ spec[2],
626
+ defaulted_vals,
627
+ formatvalue=lambda x: "=" + str(x),
628
+ )
629
+
630
+ if spec[0]:
631
+ apply_kw_proxied = compat.inspect_formatargspec(
632
+ name_args[1:],
633
+ spec[1],
634
+ spec[2],
635
+ defaulted_vals,
636
+ formatvalue=lambda x: "=" + str(x),
637
+ )
638
+ else:
639
+ apply_kw_proxied = apply_kw
640
+
641
+ if grouped:
642
+ return dict(
643
+ grouped_args=args,
644
+ self_arg=self_arg,
645
+ apply_pos=apply_pos,
646
+ apply_kw=apply_kw,
647
+ apply_pos_proxied=apply_pos_proxied,
648
+ apply_kw_proxied=apply_kw_proxied,
649
+ )
650
+ else:
651
+ return dict(
652
+ grouped_args=args,
653
+ self_arg=self_arg,
654
+ apply_pos=apply_pos[1:-1],
655
+ apply_kw=apply_kw[1:-1],
656
+ apply_pos_proxied=apply_pos_proxied[1:-1],
657
+ apply_kw_proxied=apply_kw_proxied[1:-1],
658
+ )
659
+
660
+
661
+ def format_argspec_init(method, grouped=True):
662
+ """format_argspec_plus with considerations for typical __init__ methods
663
+
664
+ Wraps format_argspec_plus with error handling strategies for typical
665
+ __init__ cases::
666
+
667
+ object.__init__ -> (self)
668
+ other unreflectable (usually C) -> (self, *args, **kwargs)
669
+
670
+ """
671
+ if method is object.__init__:
672
+ grouped_args = "(self)"
673
+ args = "(self)" if grouped else "self"
674
+ proxied = "()" if grouped else ""
675
+ else:
676
+ try:
677
+ return format_argspec_plus(method, grouped=grouped)
678
+ except TypeError:
679
+ grouped_args = "(self, *args, **kwargs)"
680
+ args = grouped_args if grouped else "self, *args, **kwargs"
681
+ proxied = "(*args, **kwargs)" if grouped else "*args, **kwargs"
682
+ return dict(
683
+ self_arg="self",
684
+ grouped_args=grouped_args,
685
+ apply_pos=args,
686
+ apply_kw=args,
687
+ apply_pos_proxied=proxied,
688
+ apply_kw_proxied=proxied,
689
+ )
690
+
691
+
692
+ def create_proxy_methods(
693
+ target_cls: Type[Any],
694
+ target_cls_sphinx_name: str,
695
+ proxy_cls_sphinx_name: str,
696
+ classmethods: Sequence[str] = (),
697
+ methods: Sequence[str] = (),
698
+ attributes: Sequence[str] = (),
699
+ use_intermediate_variable: Sequence[str] = (),
700
+ ) -> Callable[[_T], _T]:
701
+ """A class decorator indicating attributes should refer to a proxy
702
+ class.
703
+
704
+ This decorator is now a "marker" that does nothing at runtime. Instead,
705
+ it is consumed by the tools/generate_proxy_methods.py script to
706
+ statically generate proxy methods and attributes that are fully
707
+ recognized by typing tools such as mypy.
708
+
709
+ """
710
+
711
+ def decorate(cls):
712
+ return cls
713
+
714
+ return decorate
715
+
716
+
717
+ def getargspec_init(method):
718
+ """inspect.getargspec with considerations for typical __init__ methods
719
+
720
+ Wraps inspect.getargspec with error handling for typical __init__ cases::
721
+
722
+ object.__init__ -> (self)
723
+ other unreflectable (usually C) -> (self, *args, **kwargs)
724
+
725
+ """
726
+ try:
727
+ return compat.inspect_getfullargspec(method)
728
+ except TypeError:
729
+ if method is object.__init__:
730
+ return (["self"], None, None, None)
731
+ else:
732
+ return (["self"], "args", "kwargs", None)
733
+
734
+
735
+ def unbound_method_to_callable(func_or_cls):
736
+ """Adjust the incoming callable such that a 'self' argument is not
737
+ required.
738
+
739
+ """
740
+
741
+ if isinstance(func_or_cls, types.MethodType) and not func_or_cls.__self__:
742
+ return func_or_cls.__func__
743
+ else:
744
+ return func_or_cls
745
+
746
+
747
+ def generic_repr(
748
+ obj: Any,
749
+ additional_kw: Sequence[Tuple[str, Any]] = (),
750
+ to_inspect: Optional[Union[object, List[object]]] = None,
751
+ omit_kwarg: Sequence[str] = (),
752
+ ) -> str:
753
+ """Produce a __repr__() based on direct association of the __init__()
754
+ specification vs. same-named attributes present.
755
+
756
+ """
757
+ if to_inspect is None:
758
+ to_inspect = [obj]
759
+ else:
760
+ to_inspect = _collections.to_list(to_inspect)
761
+
762
+ missing = object()
763
+
764
+ pos_args = []
765
+ kw_args: _collections.OrderedDict[str, Any] = _collections.OrderedDict()
766
+ vargs = None
767
+ for i, insp in enumerate(to_inspect):
768
+ try:
769
+ spec = compat.inspect_getfullargspec(insp.__init__)
770
+ except TypeError:
771
+ continue
772
+ else:
773
+ default_len = len(spec.defaults) if spec.defaults else 0
774
+ if i == 0:
775
+ if spec.varargs:
776
+ vargs = spec.varargs
777
+ if default_len:
778
+ pos_args.extend(spec.args[1:-default_len])
779
+ else:
780
+ pos_args.extend(spec.args[1:])
781
+ else:
782
+ kw_args.update(
783
+ [(arg, missing) for arg in spec.args[1:-default_len]]
784
+ )
785
+
786
+ if default_len:
787
+ assert spec.defaults
788
+ kw_args.update(
789
+ [
790
+ (arg, default)
791
+ for arg, default in zip(
792
+ spec.args[-default_len:], spec.defaults
793
+ )
794
+ ]
795
+ )
796
+ output: List[str] = []
797
+
798
+ output.extend(repr(getattr(obj, arg, None)) for arg in pos_args)
799
+
800
+ if vargs is not None and hasattr(obj, vargs):
801
+ output.extend([repr(val) for val in getattr(obj, vargs)])
802
+
803
+ for arg, defval in kw_args.items():
804
+ if arg in omit_kwarg:
805
+ continue
806
+ try:
807
+ val = getattr(obj, arg, missing)
808
+ if val is not missing and val != defval:
809
+ output.append("%s=%r" % (arg, val))
810
+ except Exception:
811
+ pass
812
+
813
+ if additional_kw:
814
+ for arg, defval in additional_kw:
815
+ try:
816
+ val = getattr(obj, arg, missing)
817
+ if val is not missing and val != defval:
818
+ output.append("%s=%r" % (arg, val))
819
+ except Exception:
820
+ pass
821
+
822
+ return "%s(%s)" % (obj.__class__.__name__, ", ".join(output))
823
+
824
+
825
+ class portable_instancemethod:
826
+ """Turn an instancemethod into a (parent, name) pair
827
+ to produce a serializable callable.
828
+
829
+ """
830
+
831
+ __slots__ = "target", "name", "kwargs", "__weakref__"
832
+
833
+ def __getstate__(self):
834
+ return {
835
+ "target": self.target,
836
+ "name": self.name,
837
+ "kwargs": self.kwargs,
838
+ }
839
+
840
+ def __setstate__(self, state):
841
+ self.target = state["target"]
842
+ self.name = state["name"]
843
+ self.kwargs = state.get("kwargs", ())
844
+
845
+ def __init__(self, meth, kwargs=()):
846
+ self.target = meth.__self__
847
+ self.name = meth.__name__
848
+ self.kwargs = kwargs
849
+
850
+ def __call__(self, *arg, **kw):
851
+ kw.update(self.kwargs)
852
+ return getattr(self.target, self.name)(*arg, **kw)
853
+
854
+
855
+ def class_hierarchy(cls):
856
+ """Return an unordered sequence of all classes related to cls.
857
+
858
+ Traverses diamond hierarchies.
859
+
860
+ Fibs slightly: subclasses of builtin types are not returned. Thus
861
+ class_hierarchy(class A(object)) returns (A, object), not A plus every
862
+ class systemwide that derives from object.
863
+
864
+ """
865
+
866
+ hier = {cls}
867
+ process = list(cls.__mro__)
868
+ while process:
869
+ c = process.pop()
870
+ bases = (_ for _ in c.__bases__ if _ not in hier)
871
+
872
+ for b in bases:
873
+ process.append(b)
874
+ hier.add(b)
875
+
876
+ if c.__module__ == "builtins" or not hasattr(c, "__subclasses__"):
877
+ continue
878
+
879
+ for s in [
880
+ _
881
+ for _ in (
882
+ c.__subclasses__()
883
+ if not issubclass(c, type)
884
+ else c.__subclasses__(c)
885
+ )
886
+ if _ not in hier
887
+ ]:
888
+ process.append(s)
889
+ hier.add(s)
890
+ return list(hier)
891
+
892
+
893
+ def iterate_attributes(cls):
894
+ """iterate all the keys and attributes associated
895
+ with a class, without using getattr().
896
+
897
+ Does not use getattr() so that class-sensitive
898
+ descriptors (i.e. property.__get__()) are not called.
899
+
900
+ """
901
+ keys = dir(cls)
902
+ for key in keys:
903
+ for c in cls.__mro__:
904
+ if key in c.__dict__:
905
+ yield (key, c.__dict__[key])
906
+ break
907
+
908
+
909
+ def monkeypatch_proxied_specials(
910
+ into_cls,
911
+ from_cls,
912
+ skip=None,
913
+ only=None,
914
+ name="self.proxy",
915
+ from_instance=None,
916
+ ):
917
+ """Automates delegation of __specials__ for a proxying type."""
918
+
919
+ if only:
920
+ dunders = only
921
+ else:
922
+ if skip is None:
923
+ skip = (
924
+ "__slots__",
925
+ "__del__",
926
+ "__getattribute__",
927
+ "__metaclass__",
928
+ "__getstate__",
929
+ "__setstate__",
930
+ )
931
+ dunders = [
932
+ m
933
+ for m in dir(from_cls)
934
+ if (
935
+ m.startswith("__")
936
+ and m.endswith("__")
937
+ and not hasattr(into_cls, m)
938
+ and m not in skip
939
+ )
940
+ ]
941
+
942
+ for method in dunders:
943
+ try:
944
+ maybe_fn = getattr(from_cls, method)
945
+ if not hasattr(maybe_fn, "__call__"):
946
+ continue
947
+ maybe_fn = getattr(maybe_fn, "__func__", maybe_fn)
948
+ fn = cast(types.FunctionType, maybe_fn)
949
+
950
+ except AttributeError:
951
+ continue
952
+ try:
953
+ spec = compat.inspect_getfullargspec(fn)
954
+ fn_args = compat.inspect_formatargspec(spec[0])
955
+ d_args = compat.inspect_formatargspec(spec[0][1:])
956
+ except TypeError:
957
+ fn_args = "(self, *args, **kw)"
958
+ d_args = "(*args, **kw)"
959
+
960
+ py = (
961
+ "def %(method)s%(fn_args)s: "
962
+ "return %(name)s.%(method)s%(d_args)s" % locals()
963
+ )
964
+
965
+ env: Dict[str, types.FunctionType] = (
966
+ from_instance is not None and {name: from_instance} or {}
967
+ )
968
+ exec(py, env)
969
+ try:
970
+ env[method].__defaults__ = fn.__defaults__
971
+ except AttributeError:
972
+ pass
973
+ setattr(into_cls, method, env[method])
974
+
975
+
976
+ def methods_equivalent(meth1, meth2):
977
+ """Return True if the two methods are the same implementation."""
978
+
979
+ return getattr(meth1, "__func__", meth1) is getattr(
980
+ meth2, "__func__", meth2
981
+ )
982
+
983
+
984
+ def as_interface(obj, cls=None, methods=None, required=None):
985
+ """Ensure basic interface compliance for an instance or dict of callables.
986
+
987
+ Checks that ``obj`` implements public methods of ``cls`` or has members
988
+ listed in ``methods``. If ``required`` is not supplied, implementing at
989
+ least one interface method is sufficient. Methods present on ``obj`` that
990
+ are not in the interface are ignored.
991
+
992
+ If ``obj`` is a dict and ``dict`` does not meet the interface
993
+ requirements, the keys of the dictionary are inspected. Keys present in
994
+ ``obj`` that are not in the interface will raise TypeErrors.
995
+
996
+ Raises TypeError if ``obj`` does not meet the interface criteria.
997
+
998
+ In all passing cases, an object with callable members is returned. In the
999
+ simple case, ``obj`` is returned as-is; if dict processing kicks in then
1000
+ an anonymous class is returned.
1001
+
1002
+ obj
1003
+ A type, instance, or dictionary of callables.
1004
+ cls
1005
+ Optional, a type. All public methods of cls are considered the
1006
+ interface. An ``obj`` instance of cls will always pass, ignoring
1007
+ ``required``..
1008
+ methods
1009
+ Optional, a sequence of method names to consider as the interface.
1010
+ required
1011
+ Optional, a sequence of mandatory implementations. If omitted, an
1012
+ ``obj`` that provides at least one interface method is considered
1013
+ sufficient. As a convenience, required may be a type, in which case
1014
+ all public methods of the type are required.
1015
+
1016
+ """
1017
+ if not cls and not methods:
1018
+ raise TypeError("a class or collection of method names are required")
1019
+
1020
+ if isinstance(cls, type) and isinstance(obj, cls):
1021
+ return obj
1022
+
1023
+ interface = set(methods or [m for m in dir(cls) if not m.startswith("_")])
1024
+ implemented = set(dir(obj))
1025
+
1026
+ complies = operator.ge
1027
+ if isinstance(required, type):
1028
+ required = interface
1029
+ elif not required:
1030
+ required = set()
1031
+ complies = operator.gt
1032
+ else:
1033
+ required = set(required)
1034
+
1035
+ if complies(implemented.intersection(interface), required):
1036
+ return obj
1037
+
1038
+ # No dict duck typing here.
1039
+ if not isinstance(obj, dict):
1040
+ qualifier = complies is operator.gt and "any of" or "all of"
1041
+ raise TypeError(
1042
+ "%r does not implement %s: %s"
1043
+ % (obj, qualifier, ", ".join(interface))
1044
+ )
1045
+
1046
+ class AnonymousInterface:
1047
+ """A callable-holding shell."""
1048
+
1049
+ if cls:
1050
+ AnonymousInterface.__name__ = "Anonymous" + cls.__name__
1051
+ found = set()
1052
+
1053
+ for method, impl in dictlike_iteritems(obj):
1054
+ if method not in interface:
1055
+ raise TypeError("%r: unknown in this interface" % method)
1056
+ if not callable(impl):
1057
+ raise TypeError("%r=%r is not callable" % (method, impl))
1058
+ setattr(AnonymousInterface, method, staticmethod(impl))
1059
+ found.add(method)
1060
+
1061
+ if complies(found, required):
1062
+ return AnonymousInterface
1063
+
1064
+ raise TypeError(
1065
+ "dictionary does not contain required keys %s"
1066
+ % ", ".join(required - found)
1067
+ )
1068
+
1069
+
1070
+ _GFD = TypeVar("_GFD", bound="generic_fn_descriptor[Any]")
1071
+
1072
+
1073
+ class generic_fn_descriptor(Generic[_T_co]):
1074
+ """Descriptor which proxies a function when the attribute is not
1075
+ present in dict
1076
+
1077
+ This superclass is organized in a particular way with "memoized" and
1078
+ "non-memoized" implementation classes that are hidden from type checkers,
1079
+ as Mypy seems to not be able to handle seeing multiple kinds of descriptor
1080
+ classes used for the same attribute.
1081
+
1082
+ """
1083
+
1084
+ fget: Callable[..., _T_co]
1085
+ __doc__: Optional[str]
1086
+ __name__: str
1087
+
1088
+ def __init__(self, fget: Callable[..., _T_co], doc: Optional[str] = None):
1089
+ self.fget = fget
1090
+ self.__doc__ = doc or fget.__doc__
1091
+ self.__name__ = fget.__name__
1092
+
1093
+ @overload
1094
+ def __get__(self: _GFD, obj: None, cls: Any) -> _GFD: ...
1095
+
1096
+ @overload
1097
+ def __get__(self, obj: object, cls: Any) -> _T_co: ...
1098
+
1099
+ def __get__(self: _GFD, obj: Any, cls: Any) -> Union[_GFD, _T_co]:
1100
+ raise NotImplementedError()
1101
+
1102
+ if TYPE_CHECKING:
1103
+
1104
+ def __set__(self, instance: Any, value: Any) -> None: ...
1105
+
1106
+ def __delete__(self, instance: Any) -> None: ...
1107
+
1108
+ def _reset(self, obj: Any) -> None:
1109
+ raise NotImplementedError()
1110
+
1111
+ @classmethod
1112
+ def reset(cls, obj: Any, name: str) -> None:
1113
+ raise NotImplementedError()
1114
+
1115
+
1116
+ class _non_memoized_property(generic_fn_descriptor[_T_co]):
1117
+ """a plain descriptor that proxies a function.
1118
+
1119
+ primary rationale is to provide a plain attribute that's
1120
+ compatible with memoized_property which is also recognized as equivalent
1121
+ by mypy.
1122
+
1123
+ """
1124
+
1125
+ if not TYPE_CHECKING:
1126
+
1127
+ def __get__(self, obj, cls):
1128
+ if obj is None:
1129
+ return self
1130
+ return self.fget(obj)
1131
+
1132
+
1133
+ class _memoized_property(generic_fn_descriptor[_T_co]):
1134
+ """A read-only @property that is only evaluated once."""
1135
+
1136
+ if not TYPE_CHECKING:
1137
+
1138
+ def __get__(self, obj, cls):
1139
+ if obj is None:
1140
+ return self
1141
+ obj.__dict__[self.__name__] = result = self.fget(obj)
1142
+ return result
1143
+
1144
+ def _reset(self, obj):
1145
+ _memoized_property.reset(obj, self.__name__)
1146
+
1147
+ @classmethod
1148
+ def reset(cls, obj, name):
1149
+ obj.__dict__.pop(name, None)
1150
+
1151
+
1152
+ # despite many attempts to get Mypy to recognize an overridden descriptor
1153
+ # where one is memoized and the other isn't, there seems to be no reliable
1154
+ # way other than completely deceiving the type checker into thinking there
1155
+ # is just one single descriptor type everywhere. Otherwise, if a superclass
1156
+ # has non-memoized and subclass has memoized, that requires
1157
+ # "class memoized(non_memoized)". but then if a superclass has memoized and
1158
+ # superclass has non-memoized, the class hierarchy of the descriptors
1159
+ # would need to be reversed; "class non_memoized(memoized)". so there's no
1160
+ # way to achieve this.
1161
+ # additional issues, RO properties:
1162
+ # https://github.com/python/mypy/issues/12440
1163
+ if TYPE_CHECKING:
1164
+ # allow memoized and non-memoized to be freely mixed by having them
1165
+ # be the same class
1166
+ memoized_property = generic_fn_descriptor
1167
+ non_memoized_property = generic_fn_descriptor
1168
+
1169
+ # for read only situations, mypy only sees @property as read only.
1170
+ # read only is needed when a subtype specializes the return type
1171
+ # of a property, meaning assignment needs to be disallowed
1172
+ ro_memoized_property = property
1173
+ ro_non_memoized_property = property
1174
+
1175
+ else:
1176
+ memoized_property = ro_memoized_property = _memoized_property
1177
+ non_memoized_property = ro_non_memoized_property = _non_memoized_property
1178
+
1179
+
1180
+ def memoized_instancemethod(fn: _F) -> _F:
1181
+ """Decorate a method memoize its return value.
1182
+
1183
+ Best applied to no-arg methods: memoization is not sensitive to
1184
+ argument values, and will always return the same value even when
1185
+ called with different arguments.
1186
+
1187
+ """
1188
+
1189
+ def oneshot(self, *args, **kw):
1190
+ result = fn(self, *args, **kw)
1191
+
1192
+ def memo(*a, **kw):
1193
+ return result
1194
+
1195
+ memo.__name__ = fn.__name__
1196
+ memo.__doc__ = fn.__doc__
1197
+ self.__dict__[fn.__name__] = memo
1198
+ return result
1199
+
1200
+ return update_wrapper(oneshot, fn) # type: ignore
1201
+
1202
+
1203
+ class HasMemoized:
1204
+ """A mixin class that maintains the names of memoized elements in a
1205
+ collection for easy cache clearing, generative, etc.
1206
+
1207
+ """
1208
+
1209
+ if not TYPE_CHECKING:
1210
+ # support classes that want to have __slots__ with an explicit
1211
+ # slot for __dict__. not sure if that requires base __slots__ here.
1212
+ __slots__ = ()
1213
+
1214
+ _memoized_keys: FrozenSet[str] = frozenset()
1215
+
1216
+ def _reset_memoizations(self) -> None:
1217
+ for elem in self._memoized_keys:
1218
+ self.__dict__.pop(elem, None)
1219
+
1220
+ def _assert_no_memoizations(self) -> None:
1221
+ for elem in self._memoized_keys:
1222
+ assert elem not in self.__dict__
1223
+
1224
+ def _set_memoized_attribute(self, key: str, value: Any) -> None:
1225
+ self.__dict__[key] = value
1226
+ self._memoized_keys |= {key}
1227
+
1228
+ class memoized_attribute(memoized_property[_T]):
1229
+ """A read-only @property that is only evaluated once.
1230
+
1231
+ :meta private:
1232
+
1233
+ """
1234
+
1235
+ fget: Callable[..., _T]
1236
+ __doc__: Optional[str]
1237
+ __name__: str
1238
+
1239
+ def __init__(self, fget: Callable[..., _T], doc: Optional[str] = None):
1240
+ self.fget = fget
1241
+ self.__doc__ = doc or fget.__doc__
1242
+ self.__name__ = fget.__name__
1243
+
1244
+ @overload
1245
+ def __get__(self: _MA, obj: None, cls: Any) -> _MA: ...
1246
+
1247
+ @overload
1248
+ def __get__(self, obj: Any, cls: Any) -> _T: ...
1249
+
1250
+ def __get__(self, obj, cls):
1251
+ if obj is None:
1252
+ return self
1253
+ obj.__dict__[self.__name__] = result = self.fget(obj)
1254
+ obj._memoized_keys |= {self.__name__}
1255
+ return result
1256
+
1257
+ @classmethod
1258
+ def memoized_instancemethod(cls, fn: _F) -> _F:
1259
+ """Decorate a method memoize its return value.
1260
+
1261
+ :meta private:
1262
+
1263
+ """
1264
+
1265
+ def oneshot(self: Any, *args: Any, **kw: Any) -> Any:
1266
+ result = fn(self, *args, **kw)
1267
+
1268
+ def memo(*a, **kw):
1269
+ return result
1270
+
1271
+ memo.__name__ = fn.__name__
1272
+ memo.__doc__ = fn.__doc__
1273
+ self.__dict__[fn.__name__] = memo
1274
+ self._memoized_keys |= {fn.__name__}
1275
+ return result
1276
+
1277
+ return update_wrapper(oneshot, fn) # type: ignore
1278
+
1279
+
1280
+ if TYPE_CHECKING:
1281
+ HasMemoized_ro_memoized_attribute = property
1282
+ else:
1283
+ HasMemoized_ro_memoized_attribute = HasMemoized.memoized_attribute
1284
+
1285
+
1286
+ class MemoizedSlots:
1287
+ """Apply memoized items to an object using a __getattr__ scheme.
1288
+
1289
+ This allows the functionality of memoized_property and
1290
+ memoized_instancemethod to be available to a class using __slots__.
1291
+
1292
+ """
1293
+
1294
+ __slots__ = ()
1295
+
1296
+ def _fallback_getattr(self, key):
1297
+ raise AttributeError(key)
1298
+
1299
+ def __getattr__(self, key: str) -> Any:
1300
+ if key.startswith("_memoized_attr_") or key.startswith(
1301
+ "_memoized_method_"
1302
+ ):
1303
+ raise AttributeError(key)
1304
+ # to avoid recursion errors when interacting with other __getattr__
1305
+ # schemes that refer to this one, when testing for memoized method
1306
+ # look at __class__ only rather than going into __getattr__ again.
1307
+ elif hasattr(self.__class__, f"_memoized_attr_{key}"):
1308
+ value = getattr(self, f"_memoized_attr_{key}")()
1309
+ setattr(self, key, value)
1310
+ return value
1311
+ elif hasattr(self.__class__, f"_memoized_method_{key}"):
1312
+ fn = getattr(self, f"_memoized_method_{key}")
1313
+
1314
+ def oneshot(*args, **kw):
1315
+ result = fn(*args, **kw)
1316
+
1317
+ def memo(*a, **kw):
1318
+ return result
1319
+
1320
+ memo.__name__ = fn.__name__
1321
+ memo.__doc__ = fn.__doc__
1322
+ setattr(self, key, memo)
1323
+ return result
1324
+
1325
+ oneshot.__doc__ = fn.__doc__
1326
+ return oneshot
1327
+ else:
1328
+ return self._fallback_getattr(key)
1329
+
1330
+
1331
+ # from paste.deploy.converters
1332
+ def asbool(obj: Any) -> bool:
1333
+ if isinstance(obj, str):
1334
+ obj = obj.strip().lower()
1335
+ if obj in ["true", "yes", "on", "y", "t", "1"]:
1336
+ return True
1337
+ elif obj in ["false", "no", "off", "n", "f", "0"]:
1338
+ return False
1339
+ else:
1340
+ raise ValueError("String is not true/false: %r" % obj)
1341
+ return bool(obj)
1342
+
1343
+
1344
+ def bool_or_str(*text: str) -> Callable[[str], Union[str, bool]]:
1345
+ """Return a callable that will evaluate a string as
1346
+ boolean, or one of a set of "alternate" string values.
1347
+
1348
+ """
1349
+
1350
+ def bool_or_value(obj: str) -> Union[str, bool]:
1351
+ if obj in text:
1352
+ return obj
1353
+ else:
1354
+ return asbool(obj)
1355
+
1356
+ return bool_or_value
1357
+
1358
+
1359
+ def asint(value: Any) -> Optional[int]:
1360
+ """Coerce to integer."""
1361
+
1362
+ if value is None:
1363
+ return value
1364
+ return int(value)
1365
+
1366
+
1367
+ def coerce_kw_type(
1368
+ kw: Dict[str, Any],
1369
+ key: str,
1370
+ type_: Type[Any],
1371
+ flexi_bool: bool = True,
1372
+ dest: Optional[Dict[str, Any]] = None,
1373
+ ) -> None:
1374
+ r"""If 'key' is present in dict 'kw', coerce its value to type 'type\_' if
1375
+ necessary. If 'flexi_bool' is True, the string '0' is considered false
1376
+ when coercing to boolean.
1377
+ """
1378
+
1379
+ if dest is None:
1380
+ dest = kw
1381
+
1382
+ if (
1383
+ key in kw
1384
+ and (not isinstance(type_, type) or not isinstance(kw[key], type_))
1385
+ and kw[key] is not None
1386
+ ):
1387
+ if type_ is bool and flexi_bool:
1388
+ dest[key] = asbool(kw[key])
1389
+ else:
1390
+ dest[key] = type_(kw[key])
1391
+
1392
+
1393
+ def constructor_key(obj: Any, cls: Type[Any]) -> Tuple[Any, ...]:
1394
+ """Produce a tuple structure that is cacheable using the __dict__ of
1395
+ obj to retrieve values
1396
+
1397
+ """
1398
+ names = get_cls_kwargs(cls)
1399
+ return (cls,) + tuple(
1400
+ (k, obj.__dict__[k]) for k in names if k in obj.__dict__
1401
+ )
1402
+
1403
+
1404
+ def constructor_copy(obj: _T, cls: Type[_T], *args: Any, **kw: Any) -> _T:
1405
+ """Instantiate cls using the __dict__ of obj as constructor arguments.
1406
+
1407
+ Uses inspect to match the named arguments of ``cls``.
1408
+
1409
+ """
1410
+
1411
+ names = get_cls_kwargs(cls)
1412
+ kw.update(
1413
+ (k, obj.__dict__[k]) for k in names.difference(kw) if k in obj.__dict__
1414
+ )
1415
+ return cls(*args, **kw)
1416
+
1417
+
1418
+ def counter() -> Callable[[], int]:
1419
+ """Return a threadsafe counter function."""
1420
+
1421
+ lock = threading.Lock()
1422
+ counter = itertools.count(1)
1423
+
1424
+ # avoid the 2to3 "next" transformation...
1425
+ def _next():
1426
+ with lock:
1427
+ return next(counter)
1428
+
1429
+ return _next
1430
+
1431
+
1432
+ def duck_type_collection(
1433
+ specimen: Any, default: Optional[Type[Any]] = None
1434
+ ) -> Optional[Type[Any]]:
1435
+ """Given an instance or class, guess if it is or is acting as one of
1436
+ the basic collection types: list, set and dict. If the __emulates__
1437
+ property is present, return that preferentially.
1438
+ """
1439
+
1440
+ if hasattr(specimen, "__emulates__"):
1441
+ # canonicalize set vs sets.Set to a standard: the builtin set
1442
+ if specimen.__emulates__ is not None and issubclass(
1443
+ specimen.__emulates__, set
1444
+ ):
1445
+ return set
1446
+ else:
1447
+ return specimen.__emulates__ # type: ignore
1448
+
1449
+ isa = issubclass if isinstance(specimen, type) else isinstance
1450
+ if isa(specimen, list):
1451
+ return list
1452
+ elif isa(specimen, set):
1453
+ return set
1454
+ elif isa(specimen, dict):
1455
+ return dict
1456
+
1457
+ if hasattr(specimen, "append"):
1458
+ return list
1459
+ elif hasattr(specimen, "add"):
1460
+ return set
1461
+ elif hasattr(specimen, "set"):
1462
+ return dict
1463
+ else:
1464
+ return default
1465
+
1466
+
1467
+ def assert_arg_type(
1468
+ arg: Any, argtype: Union[Tuple[Type[Any], ...], Type[Any]], name: str
1469
+ ) -> Any:
1470
+ if isinstance(arg, argtype):
1471
+ return arg
1472
+ else:
1473
+ if isinstance(argtype, tuple):
1474
+ raise exc.ArgumentError(
1475
+ "Argument '%s' is expected to be one of type %s, got '%s'"
1476
+ % (name, " or ".join("'%s'" % a for a in argtype), type(arg))
1477
+ )
1478
+ else:
1479
+ raise exc.ArgumentError(
1480
+ "Argument '%s' is expected to be of type '%s', got '%s'"
1481
+ % (name, argtype, type(arg))
1482
+ )
1483
+
1484
+
1485
+ def dictlike_iteritems(dictlike):
1486
+ """Return a (key, value) iterator for almost any dict-like object."""
1487
+
1488
+ if hasattr(dictlike, "items"):
1489
+ return list(dictlike.items())
1490
+
1491
+ getter = getattr(dictlike, "__getitem__", getattr(dictlike, "get", None))
1492
+ if getter is None:
1493
+ raise TypeError("Object '%r' is not dict-like" % dictlike)
1494
+
1495
+ if hasattr(dictlike, "iterkeys"):
1496
+
1497
+ def iterator():
1498
+ for key in dictlike.iterkeys():
1499
+ assert getter is not None
1500
+ yield key, getter(key)
1501
+
1502
+ return iterator()
1503
+ elif hasattr(dictlike, "keys"):
1504
+ return iter((key, getter(key)) for key in dictlike.keys())
1505
+ else:
1506
+ raise TypeError("Object '%r' is not dict-like" % dictlike)
1507
+
1508
+
1509
+ class classproperty(property):
1510
+ """A decorator that behaves like @property except that operates
1511
+ on classes rather than instances.
1512
+
1513
+ The decorator is currently special when using the declarative
1514
+ module, but note that the
1515
+ :class:`~.sqlalchemy.ext.declarative.declared_attr`
1516
+ decorator should be used for this purpose with declarative.
1517
+
1518
+ """
1519
+
1520
+ fget: Callable[[Any], Any]
1521
+
1522
+ def __init__(self, fget: Callable[[Any], Any], *arg: Any, **kw: Any):
1523
+ super().__init__(fget, *arg, **kw)
1524
+ self.__doc__ = fget.__doc__
1525
+
1526
+ def __get__(self, obj: Any, cls: Optional[type] = None) -> Any:
1527
+ return self.fget(cls)
1528
+
1529
+
1530
+ class hybridproperty(Generic[_T]):
1531
+ def __init__(self, func: Callable[..., _T]):
1532
+ self.func = func
1533
+ self.clslevel = func
1534
+
1535
+ def __get__(self, instance: Any, owner: Any) -> _T:
1536
+ if instance is None:
1537
+ clsval = self.clslevel(owner)
1538
+ return clsval
1539
+ else:
1540
+ return self.func(instance)
1541
+
1542
+ def classlevel(self, func: Callable[..., Any]) -> hybridproperty[_T]:
1543
+ self.clslevel = func
1544
+ return self
1545
+
1546
+
1547
+ class rw_hybridproperty(Generic[_T]):
1548
+ def __init__(self, func: Callable[..., _T]):
1549
+ self.func = func
1550
+ self.clslevel = func
1551
+ self.setfn: Optional[Callable[..., Any]] = None
1552
+
1553
+ def __get__(self, instance: Any, owner: Any) -> _T:
1554
+ if instance is None:
1555
+ clsval = self.clslevel(owner)
1556
+ return clsval
1557
+ else:
1558
+ return self.func(instance)
1559
+
1560
+ def __set__(self, instance: Any, value: Any) -> None:
1561
+ assert self.setfn is not None
1562
+ self.setfn(instance, value)
1563
+
1564
+ def setter(self, func: Callable[..., Any]) -> rw_hybridproperty[_T]:
1565
+ self.setfn = func
1566
+ return self
1567
+
1568
+ def classlevel(self, func: Callable[..., Any]) -> rw_hybridproperty[_T]:
1569
+ self.clslevel = func
1570
+ return self
1571
+
1572
+
1573
+ class hybridmethod(Generic[_T]):
1574
+ """Decorate a function as cls- or instance- level."""
1575
+
1576
+ def __init__(self, func: Callable[..., _T]):
1577
+ self.func = self.__func__ = func
1578
+ self.clslevel = func
1579
+
1580
+ def __get__(self, instance: Any, owner: Any) -> Callable[..., _T]:
1581
+ if instance is None:
1582
+ return self.clslevel.__get__(owner, owner.__class__) # type:ignore
1583
+ else:
1584
+ return self.func.__get__(instance, owner) # type:ignore
1585
+
1586
+ def classlevel(self, func: Callable[..., Any]) -> hybridmethod[_T]:
1587
+ self.clslevel = func
1588
+ return self
1589
+
1590
+
1591
+ class symbol(int):
1592
+ """A constant symbol.
1593
+
1594
+ >>> symbol('foo') is symbol('foo')
1595
+ True
1596
+ >>> symbol('foo')
1597
+ <symbol 'foo>
1598
+
1599
+ A slight refinement of the MAGICCOOKIE=object() pattern. The primary
1600
+ advantage of symbol() is its repr(). They are also singletons.
1601
+
1602
+ Repeated calls of symbol('name') will all return the same instance.
1603
+
1604
+ """
1605
+
1606
+ name: str
1607
+
1608
+ symbols: Dict[str, symbol] = {}
1609
+ _lock = threading.Lock()
1610
+
1611
+ def __new__(
1612
+ cls,
1613
+ name: str,
1614
+ doc: Optional[str] = None,
1615
+ canonical: Optional[int] = None,
1616
+ ) -> symbol:
1617
+ with cls._lock:
1618
+ sym = cls.symbols.get(name)
1619
+ if sym is None:
1620
+ assert isinstance(name, str)
1621
+ if canonical is None:
1622
+ canonical = hash(name)
1623
+ sym = int.__new__(symbol, canonical)
1624
+ sym.name = name
1625
+ if doc:
1626
+ sym.__doc__ = doc
1627
+
1628
+ # NOTE: we should ultimately get rid of this global thing,
1629
+ # however, currently it is to support pickling. The best
1630
+ # change would be when we are on py3.11 at a minimum, we
1631
+ # switch to stdlib enum.IntFlag.
1632
+ cls.symbols[name] = sym
1633
+ else:
1634
+ if canonical and canonical != sym:
1635
+ raise TypeError(
1636
+ f"Can't replace canonical symbol for {name!r} "
1637
+ f"with new int value {canonical}"
1638
+ )
1639
+ return sym
1640
+
1641
+ def __reduce__(self):
1642
+ return symbol, (self.name, "x", int(self))
1643
+
1644
+ def __str__(self):
1645
+ return repr(self)
1646
+
1647
+ def __repr__(self):
1648
+ return f"symbol({self.name!r})"
1649
+
1650
+
1651
+ class _IntFlagMeta(type):
1652
+ def __init__(
1653
+ cls,
1654
+ classname: str,
1655
+ bases: Tuple[Type[Any], ...],
1656
+ dict_: Dict[str, Any],
1657
+ **kw: Any,
1658
+ ) -> None:
1659
+ items: List[symbol]
1660
+ cls._items = items = []
1661
+ for k, v in dict_.items():
1662
+ if re.match(r"^__.*__$", k):
1663
+ continue
1664
+ if isinstance(v, int):
1665
+ sym = symbol(k, canonical=v)
1666
+ elif not k.startswith("_"):
1667
+ raise TypeError("Expected integer values for IntFlag")
1668
+ else:
1669
+ continue
1670
+ setattr(cls, k, sym)
1671
+ items.append(sym)
1672
+
1673
+ cls.__members__ = _collections.immutabledict(
1674
+ {sym.name: sym for sym in items}
1675
+ )
1676
+
1677
+ def __iter__(self) -> Iterator[symbol]:
1678
+ raise NotImplementedError(
1679
+ "iter not implemented to ensure compatibility with "
1680
+ "Python 3.11 IntFlag. Please use __members__. See "
1681
+ "https://github.com/python/cpython/issues/99304"
1682
+ )
1683
+
1684
+
1685
+ class _FastIntFlag(metaclass=_IntFlagMeta):
1686
+ """An 'IntFlag' copycat that isn't slow when performing bitwise
1687
+ operations.
1688
+
1689
+ the ``FastIntFlag`` class will return ``enum.IntFlag`` under TYPE_CHECKING
1690
+ and ``_FastIntFlag`` otherwise.
1691
+
1692
+ """
1693
+
1694
+
1695
+ if TYPE_CHECKING:
1696
+ from enum import IntFlag
1697
+
1698
+ FastIntFlag = IntFlag
1699
+ else:
1700
+ FastIntFlag = _FastIntFlag
1701
+
1702
+
1703
+ _E = TypeVar("_E", bound=enum.Enum)
1704
+
1705
+
1706
+ def parse_user_argument_for_enum(
1707
+ arg: Any,
1708
+ choices: Dict[_E, List[Any]],
1709
+ name: str,
1710
+ resolve_symbol_names: bool = False,
1711
+ ) -> Optional[_E]:
1712
+ """Given a user parameter, parse the parameter into a chosen value
1713
+ from a list of choice objects, typically Enum values.
1714
+
1715
+ The user argument can be a string name that matches the name of a
1716
+ symbol, or the symbol object itself, or any number of alternate choices
1717
+ such as True/False/ None etc.
1718
+
1719
+ :param arg: the user argument.
1720
+ :param choices: dictionary of enum values to lists of possible
1721
+ entries for each.
1722
+ :param name: name of the argument. Used in an :class:`.ArgumentError`
1723
+ that is raised if the parameter doesn't match any available argument.
1724
+
1725
+ """
1726
+ for enum_value, choice in choices.items():
1727
+ if arg is enum_value:
1728
+ return enum_value
1729
+ elif resolve_symbol_names and arg == enum_value.name:
1730
+ return enum_value
1731
+ elif arg in choice:
1732
+ return enum_value
1733
+
1734
+ if arg is None:
1735
+ return None
1736
+
1737
+ raise exc.ArgumentError(f"Invalid value for '{name}': {arg!r}")
1738
+
1739
+
1740
+ _creation_order = 1
1741
+
1742
+
1743
+ def set_creation_order(instance: Any) -> None:
1744
+ """Assign a '_creation_order' sequence to the given instance.
1745
+
1746
+ This allows multiple instances to be sorted in order of creation
1747
+ (typically within a single thread; the counter is not particularly
1748
+ threadsafe).
1749
+
1750
+ """
1751
+ global _creation_order
1752
+ instance._creation_order = _creation_order
1753
+ _creation_order += 1
1754
+
1755
+
1756
+ def warn_exception(func: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
1757
+ """executes the given function, catches all exceptions and converts to
1758
+ a warning.
1759
+
1760
+ """
1761
+ try:
1762
+ return func(*args, **kwargs)
1763
+ except Exception:
1764
+ warn("%s('%s') ignored" % sys.exc_info()[0:2])
1765
+
1766
+
1767
+ def ellipses_string(value, len_=25):
1768
+ try:
1769
+ if len(value) > len_:
1770
+ return "%s..." % value[0:len_]
1771
+ else:
1772
+ return value
1773
+ except TypeError:
1774
+ return value
1775
+
1776
+
1777
+ class _hash_limit_string(str):
1778
+ """A string subclass that can only be hashed on a maximum amount
1779
+ of unique values.
1780
+
1781
+ This is used for warnings so that we can send out parameterized warnings
1782
+ without the __warningregistry__ of the module, or the non-overridable
1783
+ "once" registry within warnings.py, overloading memory,
1784
+
1785
+
1786
+ """
1787
+
1788
+ _hash: int
1789
+
1790
+ def __new__(
1791
+ cls, value: str, num: int, args: Sequence[Any]
1792
+ ) -> _hash_limit_string:
1793
+ interpolated = (value % args) + (
1794
+ " (this warning may be suppressed after %d occurrences)" % num
1795
+ )
1796
+ self = super().__new__(cls, interpolated)
1797
+ self._hash = hash("%s_%d" % (value, hash(interpolated) % num))
1798
+ return self
1799
+
1800
+ def __hash__(self) -> int:
1801
+ return self._hash
1802
+
1803
+ def __eq__(self, other: Any) -> bool:
1804
+ return hash(self) == hash(other)
1805
+
1806
+
1807
+ def warn(msg: str, code: Optional[str] = None) -> None:
1808
+ """Issue a warning.
1809
+
1810
+ If msg is a string, :class:`.exc.SAWarning` is used as
1811
+ the category.
1812
+
1813
+ """
1814
+ if code:
1815
+ _warnings_warn(exc.SAWarning(msg, code=code))
1816
+ else:
1817
+ _warnings_warn(msg, exc.SAWarning)
1818
+
1819
+
1820
+ def warn_limited(msg: str, args: Sequence[Any]) -> None:
1821
+ """Issue a warning with a parameterized string, limiting the number
1822
+ of registrations.
1823
+
1824
+ """
1825
+ if args:
1826
+ msg = _hash_limit_string(msg, 10, args)
1827
+ _warnings_warn(msg, exc.SAWarning)
1828
+
1829
+
1830
+ _warning_tags: Dict[CodeType, Tuple[str, Type[Warning]]] = {}
1831
+
1832
+
1833
+ def tag_method_for_warnings(
1834
+ message: str, category: Type[Warning]
1835
+ ) -> Callable[[_F], _F]:
1836
+ def go(fn):
1837
+ _warning_tags[fn.__code__] = (message, category)
1838
+ return fn
1839
+
1840
+ return go
1841
+
1842
+
1843
+ _not_sa_pattern = re.compile(r"^(?:sqlalchemy\.(?!testing)|alembic\.)")
1844
+
1845
+
1846
+ def _warnings_warn(
1847
+ message: Union[str, Warning],
1848
+ category: Optional[Type[Warning]] = None,
1849
+ stacklevel: int = 2,
1850
+ ) -> None:
1851
+ # adjust the given stacklevel to be outside of SQLAlchemy
1852
+ try:
1853
+ frame = sys._getframe(stacklevel)
1854
+ except ValueError:
1855
+ # being called from less than 3 (or given) stacklevels, weird,
1856
+ # but don't crash
1857
+ stacklevel = 0
1858
+ except:
1859
+ # _getframe() doesn't work, weird interpreter issue, weird,
1860
+ # ok, but don't crash
1861
+ stacklevel = 0
1862
+ else:
1863
+ stacklevel_found = warning_tag_found = False
1864
+ while frame is not None:
1865
+ # using __name__ here requires that we have __name__ in the
1866
+ # __globals__ of the decorated string functions we make also.
1867
+ # we generate this using {"__name__": fn.__module__}
1868
+ if not stacklevel_found and not re.match(
1869
+ _not_sa_pattern, frame.f_globals.get("__name__", "")
1870
+ ):
1871
+ # stop incrementing stack level if an out-of-SQLA line
1872
+ # were found.
1873
+ stacklevel_found = True
1874
+
1875
+ # however, for the warning tag thing, we have to keep
1876
+ # scanning up the whole traceback
1877
+
1878
+ if frame.f_code in _warning_tags:
1879
+ warning_tag_found = True
1880
+ (_suffix, _category) = _warning_tags[frame.f_code]
1881
+ category = category or _category
1882
+ message = f"{message} ({_suffix})"
1883
+
1884
+ frame = frame.f_back # type: ignore[assignment]
1885
+
1886
+ if not stacklevel_found:
1887
+ stacklevel += 1
1888
+ elif stacklevel_found and warning_tag_found:
1889
+ break
1890
+
1891
+ if category is not None:
1892
+ warnings.warn(message, category, stacklevel=stacklevel + 1)
1893
+ else:
1894
+ warnings.warn(message, stacklevel=stacklevel + 1)
1895
+
1896
+
1897
+ def only_once(
1898
+ fn: Callable[..., _T], retry_on_exception: bool
1899
+ ) -> Callable[..., Optional[_T]]:
1900
+ """Decorate the given function to be a no-op after it is called exactly
1901
+ once."""
1902
+
1903
+ once = [fn]
1904
+
1905
+ def go(*arg: Any, **kw: Any) -> Optional[_T]:
1906
+ # strong reference fn so that it isn't garbage collected,
1907
+ # which interferes with the event system's expectations
1908
+ strong_fn = fn # noqa
1909
+ if once:
1910
+ once_fn = once.pop()
1911
+ try:
1912
+ return once_fn(*arg, **kw)
1913
+ except:
1914
+ if retry_on_exception:
1915
+ once.insert(0, once_fn)
1916
+ raise
1917
+
1918
+ return None
1919
+
1920
+ return go
1921
+
1922
+
1923
+ _SQLA_RE = re.compile(r"sqlalchemy/([a-z_]+/){0,2}[a-z_]+\.py")
1924
+ _UNITTEST_RE = re.compile(r"unit(?:2|test2?/)")
1925
+
1926
+
1927
+ def chop_traceback(
1928
+ tb: List[str],
1929
+ exclude_prefix: re.Pattern[str] = _UNITTEST_RE,
1930
+ exclude_suffix: re.Pattern[str] = _SQLA_RE,
1931
+ ) -> List[str]:
1932
+ """Chop extraneous lines off beginning and end of a traceback.
1933
+
1934
+ :param tb:
1935
+ a list of traceback lines as returned by ``traceback.format_stack()``
1936
+
1937
+ :param exclude_prefix:
1938
+ a regular expression object matching lines to skip at beginning of
1939
+ ``tb``
1940
+
1941
+ :param exclude_suffix:
1942
+ a regular expression object matching lines to skip at end of ``tb``
1943
+ """
1944
+ start = 0
1945
+ end = len(tb) - 1
1946
+ while start <= end and exclude_prefix.search(tb[start]):
1947
+ start += 1
1948
+ while start <= end and exclude_suffix.search(tb[end]):
1949
+ end -= 1
1950
+ return tb[start : end + 1]
1951
+
1952
+
1953
+ NoneType = type(None)
1954
+
1955
+
1956
+ def attrsetter(attrname):
1957
+ code = "def set(obj, value): obj.%s = value" % attrname
1958
+ env = locals().copy()
1959
+ exec(code, env)
1960
+ return env["set"]
1961
+
1962
+
1963
+ _dunders = re.compile("^__.+__$")
1964
+
1965
+
1966
+ class TypingOnly:
1967
+ """A mixin class that marks a class as 'typing only', meaning it has
1968
+ absolutely no methods, attributes, or runtime functionality whatsoever.
1969
+
1970
+ """
1971
+
1972
+ __slots__ = ()
1973
+
1974
+ def __init_subclass__(cls) -> None:
1975
+ if TypingOnly in cls.__bases__:
1976
+ remaining = {
1977
+ name for name in cls.__dict__ if not _dunders.match(name)
1978
+ }
1979
+ if remaining:
1980
+ raise AssertionError(
1981
+ f"Class {cls} directly inherits TypingOnly but has "
1982
+ f"additional attributes {remaining}."
1983
+ )
1984
+ super().__init_subclass__()
1985
+
1986
+
1987
+ class EnsureKWArg:
1988
+ r"""Apply translation of functions to accept \**kw arguments if they
1989
+ don't already.
1990
+
1991
+ Used to ensure cross-compatibility with third party legacy code, for things
1992
+ like compiler visit methods that need to accept ``**kw`` arguments,
1993
+ but may have been copied from old code that didn't accept them.
1994
+
1995
+ """
1996
+
1997
+ ensure_kwarg: str
1998
+ """a regular expression that indicates method names for which the method
1999
+ should accept ``**kw`` arguments.
2000
+
2001
+ The class will scan for methods matching the name template and decorate
2002
+ them if necessary to ensure ``**kw`` parameters are accepted.
2003
+
2004
+ """
2005
+
2006
+ def __init_subclass__(cls) -> None:
2007
+ fn_reg = cls.ensure_kwarg
2008
+ clsdict = cls.__dict__
2009
+ if fn_reg:
2010
+ for key in clsdict:
2011
+ m = re.match(fn_reg, key)
2012
+ if m:
2013
+ fn = clsdict[key]
2014
+ spec = compat.inspect_getfullargspec(fn)
2015
+ if not spec.varkw:
2016
+ wrapped = cls._wrap_w_kw(fn)
2017
+ setattr(cls, key, wrapped)
2018
+ super().__init_subclass__()
2019
+
2020
+ @classmethod
2021
+ def _wrap_w_kw(cls, fn: Callable[..., Any]) -> Callable[..., Any]:
2022
+ def wrap(*arg: Any, **kw: Any) -> Any:
2023
+ return fn(*arg)
2024
+
2025
+ return update_wrapper(wrap, fn)
2026
+
2027
+
2028
+ def wrap_callable(wrapper, fn):
2029
+ """Augment functools.update_wrapper() to work with objects with
2030
+ a ``__call__()`` method.
2031
+
2032
+ :param fn:
2033
+ object with __call__ method
2034
+
2035
+ """
2036
+ if hasattr(fn, "__name__"):
2037
+ return update_wrapper(wrapper, fn)
2038
+ else:
2039
+ _f = wrapper
2040
+ _f.__name__ = fn.__class__.__name__
2041
+ if hasattr(fn, "__module__"):
2042
+ _f.__module__ = fn.__module__
2043
+
2044
+ if hasattr(fn.__call__, "__doc__") and fn.__call__.__doc__:
2045
+ _f.__doc__ = fn.__call__.__doc__
2046
+ elif fn.__doc__:
2047
+ _f.__doc__ = fn.__doc__
2048
+
2049
+ return _f
2050
+
2051
+
2052
+ def quoted_token_parser(value):
2053
+ """Parse a dotted identifier with accommodation for quoted names.
2054
+
2055
+ Includes support for SQL-style double quotes as a literal character.
2056
+
2057
+ E.g.::
2058
+
2059
+ >>> quoted_token_parser("name")
2060
+ ["name"]
2061
+ >>> quoted_token_parser("schema.name")
2062
+ ["schema", "name"]
2063
+ >>> quoted_token_parser('"Schema"."Name"')
2064
+ ['Schema', 'Name']
2065
+ >>> quoted_token_parser('"Schema"."Name""Foo"')
2066
+ ['Schema', 'Name""Foo']
2067
+
2068
+ """
2069
+
2070
+ if '"' not in value:
2071
+ return value.split(".")
2072
+
2073
+ # 0 = outside of quotes
2074
+ # 1 = inside of quotes
2075
+ state = 0
2076
+ result: List[List[str]] = [[]]
2077
+ idx = 0
2078
+ lv = len(value)
2079
+ while idx < lv:
2080
+ char = value[idx]
2081
+ if char == '"':
2082
+ if state == 1 and idx < lv - 1 and value[idx + 1] == '"':
2083
+ result[-1].append('"')
2084
+ idx += 1
2085
+ else:
2086
+ state ^= 1
2087
+ elif char == "." and state == 0:
2088
+ result.append([])
2089
+ else:
2090
+ result[-1].append(char)
2091
+ idx += 1
2092
+
2093
+ return ["".join(token) for token in result]
2094
+
2095
+
2096
+ def add_parameter_text(params: Any, text: str) -> Callable[[_F], _F]:
2097
+ params = _collections.to_list(params)
2098
+
2099
+ def decorate(fn):
2100
+ doc = fn.__doc__ is not None and fn.__doc__ or ""
2101
+ if doc:
2102
+ doc = inject_param_text(doc, {param: text for param in params})
2103
+ fn.__doc__ = doc
2104
+ return fn
2105
+
2106
+ return decorate
2107
+
2108
+
2109
+ def _dedent_docstring(text: str) -> str:
2110
+ split_text = text.split("\n", 1)
2111
+ if len(split_text) == 1:
2112
+ return text
2113
+ else:
2114
+ firstline, remaining = split_text
2115
+ if not firstline.startswith(" "):
2116
+ return firstline + "\n" + textwrap.dedent(remaining)
2117
+ else:
2118
+ return textwrap.dedent(text)
2119
+
2120
+
2121
+ def inject_docstring_text(
2122
+ given_doctext: Optional[str], injecttext: str, pos: int
2123
+ ) -> str:
2124
+ doctext: str = _dedent_docstring(given_doctext or "")
2125
+ lines = doctext.split("\n")
2126
+ if len(lines) == 1:
2127
+ lines.append("")
2128
+ injectlines = textwrap.dedent(injecttext).split("\n")
2129
+ if injectlines[0]:
2130
+ injectlines.insert(0, "")
2131
+
2132
+ blanks = [num for num, line in enumerate(lines) if not line.strip()]
2133
+ blanks.insert(0, 0)
2134
+
2135
+ inject_pos = blanks[min(pos, len(blanks) - 1)]
2136
+
2137
+ lines = lines[0:inject_pos] + injectlines + lines[inject_pos:]
2138
+ return "\n".join(lines)
2139
+
2140
+
2141
+ _param_reg = re.compile(r"(\s+):param (.+?):")
2142
+
2143
+
2144
+ def inject_param_text(doctext: str, inject_params: Dict[str, str]) -> str:
2145
+ doclines = collections.deque(doctext.splitlines())
2146
+ lines = []
2147
+
2148
+ # TODO: this is not working for params like ":param case_sensitive=True:"
2149
+
2150
+ to_inject = None
2151
+ while doclines:
2152
+ line = doclines.popleft()
2153
+
2154
+ m = _param_reg.match(line)
2155
+
2156
+ if to_inject is None:
2157
+ if m:
2158
+ param = m.group(2).lstrip("*")
2159
+ if param in inject_params:
2160
+ # default indent to that of :param: plus one
2161
+ indent = " " * len(m.group(1)) + " "
2162
+
2163
+ # but if the next line has text, use that line's
2164
+ # indentation
2165
+ if doclines:
2166
+ m2 = re.match(r"(\s+)\S", doclines[0])
2167
+ if m2:
2168
+ indent = " " * len(m2.group(1))
2169
+
2170
+ to_inject = indent + inject_params[param]
2171
+ elif m:
2172
+ lines.extend(["\n", to_inject, "\n"])
2173
+ to_inject = None
2174
+ elif not line.rstrip():
2175
+ lines.extend([line, to_inject, "\n"])
2176
+ to_inject = None
2177
+ elif line.endswith("::"):
2178
+ # TODO: this still won't cover if the code example itself has
2179
+ # blank lines in it, need to detect those via indentation.
2180
+ lines.extend([line, doclines.popleft()])
2181
+ continue
2182
+ lines.append(line)
2183
+
2184
+ return "\n".join(lines)
2185
+
2186
+
2187
+ def repr_tuple_names(names: List[str]) -> Optional[str]:
2188
+ """Trims a list of strings from the middle and return a string of up to
2189
+ four elements. Strings greater than 11 characters will be truncated"""
2190
+ if len(names) == 0:
2191
+ return None
2192
+ flag = len(names) <= 4
2193
+ names = names[0:4] if flag else names[0:3] + names[-1:]
2194
+ res = ["%s.." % name[:11] if len(name) > 11 else name for name in names]
2195
+ if flag:
2196
+ return ", ".join(res)
2197
+ else:
2198
+ return "%s, ..., %s" % (", ".join(res[0:3]), res[-1])
2199
+
2200
+
2201
+ def has_compiled_ext(raise_=False):
2202
+ if HAS_CYEXTENSION:
2203
+ return True
2204
+ elif raise_:
2205
+ raise ImportError(
2206
+ "cython extensions were expected to be installed, "
2207
+ "but are not present"
2208
+ )
2209
+ else:
2210
+ return False
2211
+
2212
+
2213
+ class _Missing(enum.Enum):
2214
+ Missing = enum.auto()
2215
+
2216
+
2217
+ Missing = _Missing.Missing
2218
+ MissingOr = Union[_T, Literal[_Missing.Missing]]