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,715 @@
1
+ # util/_collections.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
+ """Collection classes and helpers."""
10
+ from __future__ import annotations
11
+
12
+ import operator
13
+ import threading
14
+ import types
15
+ import typing
16
+ from typing import Any
17
+ from typing import Callable
18
+ from typing import cast
19
+ from typing import Container
20
+ from typing import Dict
21
+ from typing import FrozenSet
22
+ from typing import Generic
23
+ from typing import Iterable
24
+ from typing import Iterator
25
+ from typing import List
26
+ from typing import Mapping
27
+ from typing import NoReturn
28
+ from typing import Optional
29
+ from typing import overload
30
+ from typing import Sequence
31
+ from typing import Set
32
+ from typing import Tuple
33
+ from typing import TypeVar
34
+ from typing import Union
35
+ from typing import ValuesView
36
+ import weakref
37
+
38
+ from ._has_cy import HAS_CYEXTENSION
39
+ from .typing import is_non_string_iterable
40
+ from .typing import Literal
41
+ from .typing import Protocol
42
+
43
+ if typing.TYPE_CHECKING or not HAS_CYEXTENSION:
44
+ from ._py_collections import immutabledict as immutabledict
45
+ from ._py_collections import IdentitySet as IdentitySet
46
+ from ._py_collections import ReadOnlyContainer as ReadOnlyContainer
47
+ from ._py_collections import ImmutableDictBase as ImmutableDictBase
48
+ from ._py_collections import OrderedSet as OrderedSet
49
+ from ._py_collections import unique_list as unique_list
50
+ else:
51
+ from sqlalchemy.cyextension.immutabledict import (
52
+ ReadOnlyContainer as ReadOnlyContainer,
53
+ )
54
+ from sqlalchemy.cyextension.immutabledict import (
55
+ ImmutableDictBase as ImmutableDictBase,
56
+ )
57
+ from sqlalchemy.cyextension.immutabledict import (
58
+ immutabledict as immutabledict,
59
+ )
60
+ from sqlalchemy.cyextension.collections import IdentitySet as IdentitySet
61
+ from sqlalchemy.cyextension.collections import OrderedSet as OrderedSet
62
+ from sqlalchemy.cyextension.collections import ( # noqa
63
+ unique_list as unique_list,
64
+ )
65
+
66
+
67
+ _T = TypeVar("_T", bound=Any)
68
+ _KT = TypeVar("_KT", bound=Any)
69
+ _VT = TypeVar("_VT", bound=Any)
70
+ _T_co = TypeVar("_T_co", covariant=True)
71
+
72
+ EMPTY_SET: FrozenSet[Any] = frozenset()
73
+ NONE_SET: FrozenSet[Any] = frozenset([None])
74
+
75
+
76
+ def merge_lists_w_ordering(a: List[Any], b: List[Any]) -> List[Any]:
77
+ """merge two lists, maintaining ordering as much as possible.
78
+
79
+ this is to reconcile vars(cls) with cls.__annotations__.
80
+
81
+ Example::
82
+
83
+ >>> a = ['__tablename__', 'id', 'x', 'created_at']
84
+ >>> b = ['id', 'name', 'data', 'y', 'created_at']
85
+ >>> merge_lists_w_ordering(a, b)
86
+ ['__tablename__', 'id', 'name', 'data', 'y', 'x', 'created_at']
87
+
88
+ This is not necessarily the ordering that things had on the class,
89
+ in this case the class is::
90
+
91
+ class User(Base):
92
+ __tablename__ = "users"
93
+
94
+ id: Mapped[int] = mapped_column(primary_key=True)
95
+ name: Mapped[str]
96
+ data: Mapped[Optional[str]]
97
+ x = Column(Integer)
98
+ y: Mapped[int]
99
+ created_at: Mapped[datetime.datetime] = mapped_column()
100
+
101
+ But things are *mostly* ordered.
102
+
103
+ The algorithm could also be done by creating a partial ordering for
104
+ all items in both lists and then using topological_sort(), but that
105
+ is too much overhead.
106
+
107
+ Background on how I came up with this is at:
108
+ https://gist.github.com/zzzeek/89de958cf0803d148e74861bd682ebae
109
+
110
+ """
111
+ overlap = set(a).intersection(b)
112
+
113
+ result = []
114
+
115
+ current, other = iter(a), iter(b)
116
+
117
+ while True:
118
+ for element in current:
119
+ if element in overlap:
120
+ overlap.discard(element)
121
+ other, current = current, other
122
+ break
123
+
124
+ result.append(element)
125
+ else:
126
+ result.extend(other)
127
+ break
128
+
129
+ return result
130
+
131
+
132
+ def coerce_to_immutabledict(d: Mapping[_KT, _VT]) -> immutabledict[_KT, _VT]:
133
+ if not d:
134
+ return EMPTY_DICT
135
+ elif isinstance(d, immutabledict):
136
+ return d
137
+ else:
138
+ return immutabledict(d)
139
+
140
+
141
+ EMPTY_DICT: immutabledict[Any, Any] = immutabledict()
142
+
143
+
144
+ class FacadeDict(ImmutableDictBase[_KT, _VT]):
145
+ """A dictionary that is not publicly mutable."""
146
+
147
+ def __new__(cls, *args: Any) -> FacadeDict[Any, Any]:
148
+ new = ImmutableDictBase.__new__(cls)
149
+ return new
150
+
151
+ def copy(self) -> NoReturn:
152
+ raise NotImplementedError(
153
+ "an immutabledict shouldn't need to be copied. use dict(d) "
154
+ "if you need a mutable dictionary."
155
+ )
156
+
157
+ def __reduce__(self) -> Any:
158
+ return FacadeDict, (dict(self),)
159
+
160
+ def _insert_item(self, key: _KT, value: _VT) -> None:
161
+ """insert an item into the dictionary directly."""
162
+ dict.__setitem__(self, key, value)
163
+
164
+ def __repr__(self) -> str:
165
+ return "FacadeDict(%s)" % dict.__repr__(self)
166
+
167
+
168
+ _DT = TypeVar("_DT", bound=Any)
169
+
170
+ _F = TypeVar("_F", bound=Any)
171
+
172
+
173
+ class Properties(Generic[_T]):
174
+ """Provide a __getattr__/__setattr__ interface over a dict."""
175
+
176
+ __slots__ = ("_data",)
177
+
178
+ _data: Dict[str, _T]
179
+
180
+ def __init__(self, data: Dict[str, _T]):
181
+ object.__setattr__(self, "_data", data)
182
+
183
+ def __len__(self) -> int:
184
+ return len(self._data)
185
+
186
+ def __iter__(self) -> Iterator[_T]:
187
+ return iter(list(self._data.values()))
188
+
189
+ def __dir__(self) -> List[str]:
190
+ return dir(super()) + [str(k) for k in self._data.keys()]
191
+
192
+ def __add__(self, other: Properties[_F]) -> List[Union[_T, _F]]:
193
+ return list(self) + list(other)
194
+
195
+ def __setitem__(self, key: str, obj: _T) -> None:
196
+ self._data[key] = obj
197
+
198
+ def __getitem__(self, key: str) -> _T:
199
+ return self._data[key]
200
+
201
+ def __delitem__(self, key: str) -> None:
202
+ del self._data[key]
203
+
204
+ def __setattr__(self, key: str, obj: _T) -> None:
205
+ self._data[key] = obj
206
+
207
+ def __getstate__(self) -> Dict[str, Any]:
208
+ return {"_data": self._data}
209
+
210
+ def __setstate__(self, state: Dict[str, Any]) -> None:
211
+ object.__setattr__(self, "_data", state["_data"])
212
+
213
+ def __getattr__(self, key: str) -> _T:
214
+ try:
215
+ return self._data[key]
216
+ except KeyError:
217
+ raise AttributeError(key)
218
+
219
+ def __contains__(self, key: str) -> bool:
220
+ return key in self._data
221
+
222
+ def as_readonly(self) -> ReadOnlyProperties[_T]:
223
+ """Return an immutable proxy for this :class:`.Properties`."""
224
+
225
+ return ReadOnlyProperties(self._data)
226
+
227
+ def update(self, value: Dict[str, _T]) -> None:
228
+ self._data.update(value)
229
+
230
+ @overload
231
+ def get(self, key: str) -> Optional[_T]: ...
232
+
233
+ @overload
234
+ def get(self, key: str, default: Union[_DT, _T]) -> Union[_DT, _T]: ...
235
+
236
+ def get(
237
+ self, key: str, default: Optional[Union[_DT, _T]] = None
238
+ ) -> Optional[Union[_T, _DT]]:
239
+ if key in self:
240
+ return self[key]
241
+ else:
242
+ return default
243
+
244
+ def keys(self) -> List[str]:
245
+ return list(self._data)
246
+
247
+ def values(self) -> List[_T]:
248
+ return list(self._data.values())
249
+
250
+ def items(self) -> List[Tuple[str, _T]]:
251
+ return list(self._data.items())
252
+
253
+ def has_key(self, key: str) -> bool:
254
+ return key in self._data
255
+
256
+ def clear(self) -> None:
257
+ self._data.clear()
258
+
259
+
260
+ class OrderedProperties(Properties[_T]):
261
+ """Provide a __getattr__/__setattr__ interface with an OrderedDict
262
+ as backing store."""
263
+
264
+ __slots__ = ()
265
+
266
+ def __init__(self):
267
+ Properties.__init__(self, OrderedDict())
268
+
269
+
270
+ class ReadOnlyProperties(ReadOnlyContainer, Properties[_T]):
271
+ """Provide immutable dict/object attribute to an underlying dictionary."""
272
+
273
+ __slots__ = ()
274
+
275
+
276
+ def _ordered_dictionary_sort(d, key=None):
277
+ """Sort an OrderedDict in-place."""
278
+
279
+ items = [(k, d[k]) for k in sorted(d, key=key)]
280
+
281
+ d.clear()
282
+
283
+ d.update(items)
284
+
285
+
286
+ OrderedDict = dict
287
+ sort_dictionary = _ordered_dictionary_sort
288
+
289
+
290
+ class WeakSequence(Sequence[_T]):
291
+ def __init__(self, __elements: Sequence[_T] = ()):
292
+ # adapted from weakref.WeakKeyDictionary, prevent reference
293
+ # cycles in the collection itself
294
+ def _remove(item, selfref=weakref.ref(self)):
295
+ self = selfref()
296
+ if self is not None:
297
+ self._storage.remove(item)
298
+
299
+ self._remove = _remove
300
+ self._storage = [
301
+ weakref.ref(element, _remove) for element in __elements
302
+ ]
303
+
304
+ def append(self, item):
305
+ self._storage.append(weakref.ref(item, self._remove))
306
+
307
+ def __len__(self):
308
+ return len(self._storage)
309
+
310
+ def __iter__(self):
311
+ return (
312
+ obj for obj in (ref() for ref in self._storage) if obj is not None
313
+ )
314
+
315
+ def __getitem__(self, index):
316
+ try:
317
+ obj = self._storage[index]
318
+ except KeyError:
319
+ raise IndexError("Index %s out of range" % index)
320
+ else:
321
+ return obj()
322
+
323
+
324
+ class OrderedIdentitySet(IdentitySet):
325
+ def __init__(self, iterable: Optional[Iterable[Any]] = None):
326
+ IdentitySet.__init__(self)
327
+ self._members = OrderedDict()
328
+ if iterable:
329
+ for o in iterable:
330
+ self.add(o)
331
+
332
+
333
+ class PopulateDict(Dict[_KT, _VT]):
334
+ """A dict which populates missing values via a creation function.
335
+
336
+ Note the creation function takes a key, unlike
337
+ collections.defaultdict.
338
+
339
+ """
340
+
341
+ def __init__(self, creator: Callable[[_KT], _VT]):
342
+ self.creator = creator
343
+
344
+ def __missing__(self, key: Any) -> Any:
345
+ self[key] = val = self.creator(key)
346
+ return val
347
+
348
+
349
+ class WeakPopulateDict(Dict[_KT, _VT]):
350
+ """Like PopulateDict, but assumes a self + a method and does not create
351
+ a reference cycle.
352
+
353
+ """
354
+
355
+ def __init__(self, creator_method: types.MethodType):
356
+ self.creator = creator_method.__func__
357
+ weakself = creator_method.__self__
358
+ self.weakself = weakref.ref(weakself)
359
+
360
+ def __missing__(self, key: Any) -> Any:
361
+ self[key] = val = self.creator(self.weakself(), key)
362
+ return val
363
+
364
+
365
+ # Define collections that are capable of storing
366
+ # ColumnElement objects as hashable keys/elements.
367
+ # At this point, these are mostly historical, things
368
+ # used to be more complicated.
369
+ column_set = set
370
+ column_dict = dict
371
+ ordered_column_set = OrderedSet
372
+
373
+
374
+ class UniqueAppender(Generic[_T]):
375
+ """Appends items to a collection ensuring uniqueness.
376
+
377
+ Additional appends() of the same object are ignored. Membership is
378
+ determined by identity (``is a``) not equality (``==``).
379
+ """
380
+
381
+ __slots__ = "data", "_data_appender", "_unique"
382
+
383
+ data: Union[Iterable[_T], Set[_T], List[_T]]
384
+ _data_appender: Callable[[_T], None]
385
+ _unique: Dict[int, Literal[True]]
386
+
387
+ def __init__(
388
+ self,
389
+ data: Union[Iterable[_T], Set[_T], List[_T]],
390
+ via: Optional[str] = None,
391
+ ):
392
+ self.data = data
393
+ self._unique = {}
394
+ if via:
395
+ self._data_appender = getattr(data, via)
396
+ elif hasattr(data, "append"):
397
+ self._data_appender = cast("List[_T]", data).append
398
+ elif hasattr(data, "add"):
399
+ self._data_appender = cast("Set[_T]", data).add
400
+
401
+ def append(self, item: _T) -> None:
402
+ id_ = id(item)
403
+ if id_ not in self._unique:
404
+ self._data_appender(item)
405
+ self._unique[id_] = True
406
+
407
+ def __iter__(self) -> Iterator[_T]:
408
+ return iter(self.data)
409
+
410
+
411
+ def coerce_generator_arg(arg: Any) -> List[Any]:
412
+ if len(arg) == 1 and isinstance(arg[0], types.GeneratorType):
413
+ return list(arg[0])
414
+ else:
415
+ return cast("List[Any]", arg)
416
+
417
+
418
+ def to_list(x: Any, default: Optional[List[Any]] = None) -> List[Any]:
419
+ if x is None:
420
+ return default # type: ignore
421
+ if not is_non_string_iterable(x):
422
+ return [x]
423
+ elif isinstance(x, list):
424
+ return x
425
+ else:
426
+ return list(x)
427
+
428
+
429
+ def has_intersection(set_: Container[Any], iterable: Iterable[Any]) -> bool:
430
+ r"""return True if any items of set\_ are present in iterable.
431
+
432
+ Goes through special effort to ensure __hash__ is not called
433
+ on items in iterable that don't support it.
434
+
435
+ """
436
+ return any(i in set_ for i in iterable if i.__hash__)
437
+
438
+
439
+ def to_set(x):
440
+ if x is None:
441
+ return set()
442
+ if not isinstance(x, set):
443
+ return set(to_list(x))
444
+ else:
445
+ return x
446
+
447
+
448
+ def to_column_set(x: Any) -> Set[Any]:
449
+ if x is None:
450
+ return column_set()
451
+ if not isinstance(x, column_set):
452
+ return column_set(to_list(x))
453
+ else:
454
+ return x
455
+
456
+
457
+ def update_copy(d, _new=None, **kw):
458
+ """Copy the given dict and update with the given values."""
459
+
460
+ d = d.copy()
461
+ if _new:
462
+ d.update(_new)
463
+ d.update(**kw)
464
+ return d
465
+
466
+
467
+ def flatten_iterator(x: Iterable[_T]) -> Iterator[_T]:
468
+ """Given an iterator of which further sub-elements may also be
469
+ iterators, flatten the sub-elements into a single iterator.
470
+
471
+ """
472
+ elem: _T
473
+ for elem in x:
474
+ if not isinstance(elem, str) and hasattr(elem, "__iter__"):
475
+ yield from flatten_iterator(elem)
476
+ else:
477
+ yield elem
478
+
479
+
480
+ class LRUCache(typing.MutableMapping[_KT, _VT]):
481
+ """Dictionary with 'squishy' removal of least
482
+ recently used items.
483
+
484
+ Note that either get() or [] should be used here, but
485
+ generally its not safe to do an "in" check first as the dictionary
486
+ can change subsequent to that call.
487
+
488
+ """
489
+
490
+ __slots__ = (
491
+ "capacity",
492
+ "threshold",
493
+ "size_alert",
494
+ "_data",
495
+ "_counter",
496
+ "_mutex",
497
+ )
498
+
499
+ capacity: int
500
+ threshold: float
501
+ size_alert: Optional[Callable[[LRUCache[_KT, _VT]], None]]
502
+
503
+ def __init__(
504
+ self,
505
+ capacity: int = 100,
506
+ threshold: float = 0.5,
507
+ size_alert: Optional[Callable[..., None]] = None,
508
+ ):
509
+ self.capacity = capacity
510
+ self.threshold = threshold
511
+ self.size_alert = size_alert
512
+ self._counter = 0
513
+ self._mutex = threading.Lock()
514
+ self._data: Dict[_KT, Tuple[_KT, _VT, List[int]]] = {}
515
+
516
+ def _inc_counter(self):
517
+ self._counter += 1
518
+ return self._counter
519
+
520
+ @overload
521
+ def get(self, key: _KT) -> Optional[_VT]: ...
522
+
523
+ @overload
524
+ def get(self, key: _KT, default: Union[_VT, _T]) -> Union[_VT, _T]: ...
525
+
526
+ def get(
527
+ self, key: _KT, default: Optional[Union[_VT, _T]] = None
528
+ ) -> Optional[Union[_VT, _T]]:
529
+ item = self._data.get(key)
530
+ if item is not None:
531
+ item[2][0] = self._inc_counter()
532
+ return item[1]
533
+ else:
534
+ return default
535
+
536
+ def __getitem__(self, key: _KT) -> _VT:
537
+ item = self._data[key]
538
+ item[2][0] = self._inc_counter()
539
+ return item[1]
540
+
541
+ def __iter__(self) -> Iterator[_KT]:
542
+ return iter(self._data)
543
+
544
+ def __len__(self) -> int:
545
+ return len(self._data)
546
+
547
+ def values(self) -> ValuesView[_VT]:
548
+ return typing.ValuesView({k: i[1] for k, i in self._data.items()})
549
+
550
+ def __setitem__(self, key: _KT, value: _VT) -> None:
551
+ self._data[key] = (key, value, [self._inc_counter()])
552
+ self._manage_size()
553
+
554
+ def __delitem__(self, __v: _KT) -> None:
555
+ del self._data[__v]
556
+
557
+ @property
558
+ def size_threshold(self) -> float:
559
+ return self.capacity + self.capacity * self.threshold
560
+
561
+ def _manage_size(self) -> None:
562
+ if not self._mutex.acquire(False):
563
+ return
564
+ try:
565
+ size_alert = bool(self.size_alert)
566
+ while len(self) > self.capacity + self.capacity * self.threshold:
567
+ if size_alert:
568
+ size_alert = False
569
+ self.size_alert(self) # type: ignore
570
+ by_counter = sorted(
571
+ self._data.values(),
572
+ key=operator.itemgetter(2),
573
+ reverse=True,
574
+ )
575
+ for item in by_counter[self.capacity :]:
576
+ try:
577
+ del self._data[item[0]]
578
+ except KeyError:
579
+ # deleted elsewhere; skip
580
+ continue
581
+ finally:
582
+ self._mutex.release()
583
+
584
+
585
+ class _CreateFuncType(Protocol[_T_co]):
586
+ def __call__(self) -> _T_co: ...
587
+
588
+
589
+ class _ScopeFuncType(Protocol):
590
+ def __call__(self) -> Any: ...
591
+
592
+
593
+ class ScopedRegistry(Generic[_T]):
594
+ """A Registry that can store one or multiple instances of a single
595
+ class on the basis of a "scope" function.
596
+
597
+ The object implements ``__call__`` as the "getter", so by
598
+ calling ``myregistry()`` the contained object is returned
599
+ for the current scope.
600
+
601
+ :param createfunc:
602
+ a callable that returns a new object to be placed in the registry
603
+
604
+ :param scopefunc:
605
+ a callable that will return a key to store/retrieve an object.
606
+ """
607
+
608
+ __slots__ = "createfunc", "scopefunc", "registry"
609
+
610
+ createfunc: _CreateFuncType[_T]
611
+ scopefunc: _ScopeFuncType
612
+ registry: Any
613
+
614
+ def __init__(
615
+ self, createfunc: Callable[[], _T], scopefunc: Callable[[], Any]
616
+ ):
617
+ """Construct a new :class:`.ScopedRegistry`.
618
+
619
+ :param createfunc: A creation function that will generate
620
+ a new value for the current scope, if none is present.
621
+
622
+ :param scopefunc: A function that returns a hashable
623
+ token representing the current scope (such as, current
624
+ thread identifier).
625
+
626
+ """
627
+ self.createfunc = createfunc
628
+ self.scopefunc = scopefunc
629
+ self.registry = {}
630
+
631
+ def __call__(self) -> _T:
632
+ key = self.scopefunc()
633
+ try:
634
+ return self.registry[key] # type: ignore[no-any-return]
635
+ except KeyError:
636
+ return self.registry.setdefault(key, self.createfunc()) # type: ignore[no-any-return] # noqa: E501
637
+
638
+ def has(self) -> bool:
639
+ """Return True if an object is present in the current scope."""
640
+
641
+ return self.scopefunc() in self.registry
642
+
643
+ def set(self, obj: _T) -> None:
644
+ """Set the value for the current scope."""
645
+
646
+ self.registry[self.scopefunc()] = obj
647
+
648
+ def clear(self) -> None:
649
+ """Clear the current scope, if any."""
650
+
651
+ try:
652
+ del self.registry[self.scopefunc()]
653
+ except KeyError:
654
+ pass
655
+
656
+
657
+ class ThreadLocalRegistry(ScopedRegistry[_T]):
658
+ """A :class:`.ScopedRegistry` that uses a ``threading.local()``
659
+ variable for storage.
660
+
661
+ """
662
+
663
+ def __init__(self, createfunc: Callable[[], _T]):
664
+ self.createfunc = createfunc
665
+ self.registry = threading.local()
666
+
667
+ def __call__(self) -> _T:
668
+ try:
669
+ return self.registry.value # type: ignore[no-any-return]
670
+ except AttributeError:
671
+ val = self.registry.value = self.createfunc()
672
+ return val
673
+
674
+ def has(self) -> bool:
675
+ return hasattr(self.registry, "value")
676
+
677
+ def set(self, obj: _T) -> None:
678
+ self.registry.value = obj
679
+
680
+ def clear(self) -> None:
681
+ try:
682
+ del self.registry.value
683
+ except AttributeError:
684
+ pass
685
+
686
+
687
+ def has_dupes(sequence, target):
688
+ """Given a sequence and search object, return True if there's more
689
+ than one, False if zero or one of them.
690
+
691
+
692
+ """
693
+ # compare to .index version below, this version introduces less function
694
+ # overhead and is usually the same speed. At 15000 items (way bigger than
695
+ # a relationship-bound collection in memory usually is) it begins to
696
+ # fall behind the other version only by microseconds.
697
+ c = 0
698
+ for item in sequence:
699
+ if item is target:
700
+ c += 1
701
+ if c > 1:
702
+ return True
703
+ return False
704
+
705
+
706
+ # .index version. the two __contains__ calls as well
707
+ # as .index() and isinstance() slow this down.
708
+ # def has_dupes(sequence, target):
709
+ # if target not in sequence:
710
+ # return False
711
+ # elif not isinstance(sequence, collections_abc.Sequence):
712
+ # return False
713
+ #
714
+ # idx = sequence.index(target)
715
+ # return target in sequence[idx + 1:]