SQLAlchemy 2.1.0rc1__cp315-cp315-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 (276) hide show
  1. sqlalchemy/__init__.py +299 -0
  2. sqlalchemy/connectors/__init__.py +18 -0
  3. sqlalchemy/connectors/aioodbc.py +171 -0
  4. sqlalchemy/connectors/asyncio.py +476 -0
  5. sqlalchemy/connectors/pyodbc.py +248 -0
  6. sqlalchemy/dialects/__init__.py +62 -0
  7. sqlalchemy/dialects/_typing.py +29 -0
  8. sqlalchemy/dialects/mssql/__init__.py +88 -0
  9. sqlalchemy/dialects/mssql/aioodbc.py +63 -0
  10. sqlalchemy/dialects/mssql/base.py +4833 -0
  11. sqlalchemy/dialects/mssql/information_schema.py +345 -0
  12. sqlalchemy/dialects/mssql/json.py +140 -0
  13. sqlalchemy/dialects/mssql/mssqlpython.py +242 -0
  14. sqlalchemy/dialects/mssql/provision.py +196 -0
  15. sqlalchemy/dialects/mssql/pymssql.py +130 -0
  16. sqlalchemy/dialects/mssql/pyodbc.py +697 -0
  17. sqlalchemy/dialects/mysql/__init__.py +106 -0
  18. sqlalchemy/dialects/mysql/_mariadb_shim.py +312 -0
  19. sqlalchemy/dialects/mysql/aiomysql.py +260 -0
  20. sqlalchemy/dialects/mysql/asyncmy.py +241 -0
  21. sqlalchemy/dialects/mysql/base.py +3896 -0
  22. sqlalchemy/dialects/mysql/cymysql.py +107 -0
  23. sqlalchemy/dialects/mysql/dml.py +279 -0
  24. sqlalchemy/dialects/mysql/enumerated.py +277 -0
  25. sqlalchemy/dialects/mysql/expression.py +146 -0
  26. sqlalchemy/dialects/mysql/json.py +92 -0
  27. sqlalchemy/dialects/mysql/mariadb.py +67 -0
  28. sqlalchemy/dialects/mysql/mariadbconnector.py +314 -0
  29. sqlalchemy/dialects/mysql/mysqlconnector.py +291 -0
  30. sqlalchemy/dialects/mysql/mysqldb.py +318 -0
  31. sqlalchemy/dialects/mysql/provision.py +153 -0
  32. sqlalchemy/dialects/mysql/pymysql.py +188 -0
  33. sqlalchemy/dialects/mysql/pyodbc.py +157 -0
  34. sqlalchemy/dialects/mysql/reflection.py +724 -0
  35. sqlalchemy/dialects/mysql/reserved_words.py +570 -0
  36. sqlalchemy/dialects/mysql/types.py +845 -0
  37. sqlalchemy/dialects/oracle/__init__.py +85 -0
  38. sqlalchemy/dialects/oracle/base.py +3847 -0
  39. sqlalchemy/dialects/oracle/cx_oracle.py +1736 -0
  40. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  41. sqlalchemy/dialects/oracle/json.py +157 -0
  42. sqlalchemy/dialects/oracle/oracledb.py +898 -0
  43. sqlalchemy/dialects/oracle/provision.py +288 -0
  44. sqlalchemy/dialects/oracle/types.py +367 -0
  45. sqlalchemy/dialects/oracle/vector.py +366 -0
  46. sqlalchemy/dialects/postgresql/__init__.py +170 -0
  47. sqlalchemy/dialects/postgresql/_psycopg_common.py +232 -0
  48. sqlalchemy/dialects/postgresql/array.py +534 -0
  49. sqlalchemy/dialects/postgresql/asyncpg.py +1318 -0
  50. sqlalchemy/dialects/postgresql/base.py +5935 -0
  51. sqlalchemy/dialects/postgresql/bitstring.py +327 -0
  52. sqlalchemy/dialects/postgresql/dml.py +360 -0
  53. sqlalchemy/dialects/postgresql/ext.py +599 -0
  54. sqlalchemy/dialects/postgresql/hstore.py +422 -0
  55. sqlalchemy/dialects/postgresql/json.py +411 -0
  56. sqlalchemy/dialects/postgresql/named_types.py +535 -0
  57. sqlalchemy/dialects/postgresql/operators.py +129 -0
  58. sqlalchemy/dialects/postgresql/pg8000.py +655 -0
  59. sqlalchemy/dialects/postgresql/pg_catalog.py +345 -0
  60. sqlalchemy/dialects/postgresql/provision.py +202 -0
  61. sqlalchemy/dialects/postgresql/psycopg.py +800 -0
  62. sqlalchemy/dialects/postgresql/psycopg2.py +860 -0
  63. sqlalchemy/dialects/postgresql/psycopg2cffi.py +62 -0
  64. sqlalchemy/dialects/postgresql/ranges.py +1002 -0
  65. sqlalchemy/dialects/postgresql/types.py +388 -0
  66. sqlalchemy/dialects/sqlite/__init__.py +59 -0
  67. sqlalchemy/dialects/sqlite/aiosqlite.py +375 -0
  68. sqlalchemy/dialects/sqlite/base.py +3103 -0
  69. sqlalchemy/dialects/sqlite/dml.py +314 -0
  70. sqlalchemy/dialects/sqlite/json.py +134 -0
  71. sqlalchemy/dialects/sqlite/provision.py +237 -0
  72. sqlalchemy/dialects/sqlite/pysqlcipher.py +166 -0
  73. sqlalchemy/dialects/sqlite/pysqlite.py +959 -0
  74. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  75. sqlalchemy/engine/__init__.py +62 -0
  76. sqlalchemy/engine/_processors_cy.cp315-win32.pyd +0 -0
  77. sqlalchemy/engine/_processors_cy.py +92 -0
  78. sqlalchemy/engine/_result_cy.cp315-win32.pyd +0 -0
  79. sqlalchemy/engine/_result_cy.py +711 -0
  80. sqlalchemy/engine/_row_cy.cp315-win32.pyd +0 -0
  81. sqlalchemy/engine/_row_cy.py +232 -0
  82. sqlalchemy/engine/_util_cy.cp315-win32.pyd +0 -0
  83. sqlalchemy/engine/_util_cy.py +136 -0
  84. sqlalchemy/engine/base.py +3357 -0
  85. sqlalchemy/engine/characteristics.py +155 -0
  86. sqlalchemy/engine/create.py +877 -0
  87. sqlalchemy/engine/cursor.py +2425 -0
  88. sqlalchemy/engine/default.py +2627 -0
  89. sqlalchemy/engine/events.py +965 -0
  90. sqlalchemy/engine/interfaces.py +3636 -0
  91. sqlalchemy/engine/mock.py +133 -0
  92. sqlalchemy/engine/processors.py +83 -0
  93. sqlalchemy/engine/reflection.py +2141 -0
  94. sqlalchemy/engine/result.py +2012 -0
  95. sqlalchemy/engine/row.py +397 -0
  96. sqlalchemy/engine/strategies.py +16 -0
  97. sqlalchemy/engine/url.py +922 -0
  98. sqlalchemy/engine/util.py +164 -0
  99. sqlalchemy/event/__init__.py +26 -0
  100. sqlalchemy/event/api.py +220 -0
  101. sqlalchemy/event/attr.py +675 -0
  102. sqlalchemy/event/base.py +473 -0
  103. sqlalchemy/event/legacy.py +259 -0
  104. sqlalchemy/event/registry.py +391 -0
  105. sqlalchemy/events.py +17 -0
  106. sqlalchemy/exc.py +939 -0
  107. sqlalchemy/ext/__init__.py +10 -0
  108. sqlalchemy/ext/associationproxy.py +2073 -0
  109. sqlalchemy/ext/asyncio/__init__.py +29 -0
  110. sqlalchemy/ext/asyncio/base.py +281 -0
  111. sqlalchemy/ext/asyncio/engine.py +1487 -0
  112. sqlalchemy/ext/asyncio/exc.py +21 -0
  113. sqlalchemy/ext/asyncio/result.py +994 -0
  114. sqlalchemy/ext/asyncio/scoping.py +1679 -0
  115. sqlalchemy/ext/asyncio/session.py +2006 -0
  116. sqlalchemy/ext/automap.py +1702 -0
  117. sqlalchemy/ext/baked.py +558 -0
  118. sqlalchemy/ext/compiler.py +601 -0
  119. sqlalchemy/ext/declarative/__init__.py +65 -0
  120. sqlalchemy/ext/declarative/extensions.py +561 -0
  121. sqlalchemy/ext/horizontal_shard.py +481 -0
  122. sqlalchemy/ext/hybrid.py +1877 -0
  123. sqlalchemy/ext/indexable.py +364 -0
  124. sqlalchemy/ext/instrumentation.py +450 -0
  125. sqlalchemy/ext/mutable.py +1081 -0
  126. sqlalchemy/ext/orderinglist.py +440 -0
  127. sqlalchemy/ext/serializer.py +184 -0
  128. sqlalchemy/future/__init__.py +17 -0
  129. sqlalchemy/future/engine.py +15 -0
  130. sqlalchemy/inspection.py +188 -0
  131. sqlalchemy/log.py +279 -0
  132. sqlalchemy/orm/__init__.py +176 -0
  133. sqlalchemy/orm/_orm_constructors.py +2694 -0
  134. sqlalchemy/orm/_typing.py +180 -0
  135. sqlalchemy/orm/attributes.py +2868 -0
  136. sqlalchemy/orm/base.py +991 -0
  137. sqlalchemy/orm/bulk_persistence.py +2168 -0
  138. sqlalchemy/orm/clsregistry.py +630 -0
  139. sqlalchemy/orm/collections.py +1569 -0
  140. sqlalchemy/orm/context.py +3475 -0
  141. sqlalchemy/orm/decl_api.py +2283 -0
  142. sqlalchemy/orm/decl_base.py +2320 -0
  143. sqlalchemy/orm/dependency.py +1306 -0
  144. sqlalchemy/orm/descriptor_props.py +1183 -0
  145. sqlalchemy/orm/dynamic.py +306 -0
  146. sqlalchemy/orm/evaluator.py +378 -0
  147. sqlalchemy/orm/events.py +3387 -0
  148. sqlalchemy/orm/exc.py +237 -0
  149. sqlalchemy/orm/identity.py +302 -0
  150. sqlalchemy/orm/instrumentation.py +749 -0
  151. sqlalchemy/orm/interfaces.py +1595 -0
  152. sqlalchemy/orm/loading.py +1712 -0
  153. sqlalchemy/orm/mapped_collection.py +557 -0
  154. sqlalchemy/orm/mapper.py +4465 -0
  155. sqlalchemy/orm/path_registry.py +907 -0
  156. sqlalchemy/orm/persistence.py +1790 -0
  157. sqlalchemy/orm/properties.py +972 -0
  158. sqlalchemy/orm/query.py +3528 -0
  159. sqlalchemy/orm/relationships.py +3608 -0
  160. sqlalchemy/orm/scoping.py +2233 -0
  161. sqlalchemy/orm/session.py +5468 -0
  162. sqlalchemy/orm/state.py +1175 -0
  163. sqlalchemy/orm/state_changes.py +196 -0
  164. sqlalchemy/orm/strategies.py +3552 -0
  165. sqlalchemy/orm/strategy_options.py +2648 -0
  166. sqlalchemy/orm/sync.py +164 -0
  167. sqlalchemy/orm/unitofwork.py +797 -0
  168. sqlalchemy/orm/util.py +2461 -0
  169. sqlalchemy/orm/writeonly.py +701 -0
  170. sqlalchemy/pool/__init__.py +41 -0
  171. sqlalchemy/pool/base.py +1540 -0
  172. sqlalchemy/pool/events.py +375 -0
  173. sqlalchemy/pool/impl.py +583 -0
  174. sqlalchemy/py.typed +0 -0
  175. sqlalchemy/schema.py +75 -0
  176. sqlalchemy/sql/__init__.py +156 -0
  177. sqlalchemy/sql/_annotated_cols.py +402 -0
  178. sqlalchemy/sql/_cache_key_cy.cp315-win32.pyd +0 -0
  179. sqlalchemy/sql/_cache_key_cy.py +363 -0
  180. sqlalchemy/sql/_dml_constructors.py +132 -0
  181. sqlalchemy/sql/_elements_constructors.py +2190 -0
  182. sqlalchemy/sql/_orm_types.py +19 -0
  183. sqlalchemy/sql/_selectable_constructors.py +840 -0
  184. sqlalchemy/sql/_typing.py +500 -0
  185. sqlalchemy/sql/_util_cy.cp315-win32.pyd +0 -0
  186. sqlalchemy/sql/_util_cy.pxd +11 -0
  187. sqlalchemy/sql/_util_cy.py +127 -0
  188. sqlalchemy/sql/annotation.py +590 -0
  189. sqlalchemy/sql/base.py +2702 -0
  190. sqlalchemy/sql/cache_key.py +915 -0
  191. sqlalchemy/sql/coercions.py +1373 -0
  192. sqlalchemy/sql/compiler.py +8453 -0
  193. sqlalchemy/sql/crud.py +1816 -0
  194. sqlalchemy/sql/ddl.py +1962 -0
  195. sqlalchemy/sql/default_comparator.py +660 -0
  196. sqlalchemy/sql/dml.py +2018 -0
  197. sqlalchemy/sql/elements.py +6057 -0
  198. sqlalchemy/sql/events.py +458 -0
  199. sqlalchemy/sql/expression.py +171 -0
  200. sqlalchemy/sql/functions.py +2380 -0
  201. sqlalchemy/sql/lambdas.py +1442 -0
  202. sqlalchemy/sql/naming.py +204 -0
  203. sqlalchemy/sql/operators.py +2909 -0
  204. sqlalchemy/sql/roles.py +332 -0
  205. sqlalchemy/sql/schema.py +7075 -0
  206. sqlalchemy/sql/selectable.py +7634 -0
  207. sqlalchemy/sql/sqltypes.py +4130 -0
  208. sqlalchemy/sql/traversals.py +1041 -0
  209. sqlalchemy/sql/type_api.py +2450 -0
  210. sqlalchemy/sql/util.py +1496 -0
  211. sqlalchemy/sql/visitors.py +1153 -0
  212. sqlalchemy/testing/__init__.py +97 -0
  213. sqlalchemy/testing/assertions.py +1007 -0
  214. sqlalchemy/testing/assertsql.py +519 -0
  215. sqlalchemy/testing/asyncio.py +128 -0
  216. sqlalchemy/testing/cancellation.py +237 -0
  217. sqlalchemy/testing/config.py +440 -0
  218. sqlalchemy/testing/engines.py +482 -0
  219. sqlalchemy/testing/entities.py +117 -0
  220. sqlalchemy/testing/exclusions.py +501 -0
  221. sqlalchemy/testing/fixtures/__init__.py +30 -0
  222. sqlalchemy/testing/fixtures/base.py +426 -0
  223. sqlalchemy/testing/fixtures/mypy.py +247 -0
  224. sqlalchemy/testing/fixtures/orm.py +227 -0
  225. sqlalchemy/testing/fixtures/sql.py +538 -0
  226. sqlalchemy/testing/pickleable.py +155 -0
  227. sqlalchemy/testing/plugin/__init__.py +6 -0
  228. sqlalchemy/testing/plugin/bootstrap.py +50 -0
  229. sqlalchemy/testing/plugin/plugin_base.py +828 -0
  230. sqlalchemy/testing/plugin/pytestplugin.py +896 -0
  231. sqlalchemy/testing/profiles_file.py +350 -0
  232. sqlalchemy/testing/profiling.py +294 -0
  233. sqlalchemy/testing/provision.py +633 -0
  234. sqlalchemy/testing/requirements.py +1971 -0
  235. sqlalchemy/testing/schema.py +198 -0
  236. sqlalchemy/testing/suite/__init__.py +19 -0
  237. sqlalchemy/testing/suite/test_cte.py +237 -0
  238. sqlalchemy/testing/suite/test_ddl.py +420 -0
  239. sqlalchemy/testing/suite/test_dialect.py +776 -0
  240. sqlalchemy/testing/suite/test_insert.py +630 -0
  241. sqlalchemy/testing/suite/test_reflection.py +3815 -0
  242. sqlalchemy/testing/suite/test_results.py +660 -0
  243. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  244. sqlalchemy/testing/suite/test_select.py +2112 -0
  245. sqlalchemy/testing/suite/test_sequence.py +317 -0
  246. sqlalchemy/testing/suite/test_table_via_select.py +686 -0
  247. sqlalchemy/testing/suite/test_types.py +2271 -0
  248. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  249. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  250. sqlalchemy/testing/util.py +575 -0
  251. sqlalchemy/testing/warnings.py +52 -0
  252. sqlalchemy/types.py +75 -0
  253. sqlalchemy/util/__init__.py +165 -0
  254. sqlalchemy/util/_collections.py +688 -0
  255. sqlalchemy/util/_collections_cy.cp315-win32.pyd +0 -0
  256. sqlalchemy/util/_collections_cy.pxd +8 -0
  257. sqlalchemy/util/_collections_cy.py +516 -0
  258. sqlalchemy/util/_has_cython.py +48 -0
  259. sqlalchemy/util/_immutabledict_cy.cp315-win32.pyd +0 -0
  260. sqlalchemy/util/_immutabledict_cy.py +240 -0
  261. sqlalchemy/util/compat.py +298 -0
  262. sqlalchemy/util/concurrency.py +272 -0
  263. sqlalchemy/util/cython.py +95 -0
  264. sqlalchemy/util/deprecations.py +401 -0
  265. sqlalchemy/util/langhelpers.py +2797 -0
  266. sqlalchemy/util/preloaded.py +153 -0
  267. sqlalchemy/util/queue.py +304 -0
  268. sqlalchemy/util/tool_support.py +202 -0
  269. sqlalchemy/util/topological.py +120 -0
  270. sqlalchemy/util/typing.py +709 -0
  271. sqlalchemy-2.1.0rc1.dist-info/METADATA +270 -0
  272. sqlalchemy-2.1.0rc1.dist-info/RECORD +276 -0
  273. sqlalchemy-2.1.0rc1.dist-info/WHEEL +5 -0
  274. sqlalchemy-2.1.0rc1.dist-info/licenses/AUTHORS +30 -0
  275. sqlalchemy-2.1.0rc1.dist-info/licenses/LICENSE +19 -0
  276. sqlalchemy-2.1.0rc1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,473 @@
1
+ # event/base.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+ """Base implementation classes.
9
+
10
+ The public-facing ``Events`` serves as the base class for an event interface;
11
+ its public attributes represent different kinds of events. These attributes
12
+ are mirrored onto a ``_Dispatch`` class, which serves as a container for
13
+ collections of listener functions. These collections are represented both
14
+ at the class level of a particular ``_Dispatch`` class as well as within
15
+ instances of ``_Dispatch``.
16
+
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import typing
22
+ from typing import Any
23
+ from typing import cast
24
+ from typing import Dict
25
+ from typing import Generic
26
+ from typing import Iterator
27
+ from typing import List
28
+ from typing import Literal
29
+ from typing import Mapping
30
+ from typing import MutableMapping
31
+ from typing import Optional
32
+ from typing import overload
33
+ from typing import Tuple
34
+ from typing import Type
35
+ from typing import Union
36
+ import weakref
37
+
38
+ from .attr import _ClsLevelDispatch
39
+ from .attr import _EmptyListener
40
+ from .attr import _InstanceLevelDispatch
41
+ from .attr import _JoinedListener
42
+ from .registry import _ET
43
+ from .registry import _EventKey
44
+ from .. import util
45
+
46
+ _registrars: MutableMapping[str, List[Type[_HasEventsDispatch[Any]]]] = (
47
+ util.defaultdict(list)
48
+ )
49
+
50
+
51
+ def _is_event_name(name: str) -> bool:
52
+ # _sa_event prefix is special to support internal-only event names.
53
+ # most event names are just plain method names that aren't
54
+ # underscored.
55
+
56
+ return (
57
+ not name.startswith("_") and name != "dispatch"
58
+ ) or name.startswith("_sa_event")
59
+
60
+
61
+ class _UnpickleDispatch:
62
+ """Serializable callable that re-generates an instance of
63
+ :class:`_Dispatch` given a particular :class:`.Events` subclass.
64
+
65
+ """
66
+
67
+ def __call__(self, _instance_cls: Type[_ET]) -> _Dispatch[_ET]:
68
+ for cls in _instance_cls.__mro__:
69
+ if "dispatch" in cls.__dict__:
70
+ return cast(
71
+ "_Dispatch[_ET]", cls.__dict__["dispatch"].dispatch
72
+ )._for_class(_instance_cls)
73
+ else:
74
+ raise AttributeError("No class with a 'dispatch' member present.")
75
+
76
+
77
+ class _DispatchCommon(Generic[_ET]):
78
+ __slots__ = ()
79
+
80
+ _instance_cls: Optional[Type[_ET]]
81
+
82
+ def _join(self, other: _DispatchCommon[_ET]) -> _JoinedDispatcher[_ET]:
83
+ raise NotImplementedError()
84
+
85
+ def __getattr__(self, name: str) -> _InstanceLevelDispatch[_ET]:
86
+ raise NotImplementedError()
87
+
88
+ @property
89
+ def _events(self) -> Type[_HasEventsDispatch[_ET]]:
90
+ raise NotImplementedError()
91
+
92
+
93
+ class _Dispatch(_DispatchCommon[_ET]):
94
+ """Mirror the event listening definitions of an Events class with
95
+ listener collections.
96
+
97
+ Classes which define a "dispatch" member will return a
98
+ non-instantiated :class:`._Dispatch` subclass when the member
99
+ is accessed at the class level. When the "dispatch" member is
100
+ accessed at the instance level of its owner, an instance
101
+ of the :class:`._Dispatch` class is returned.
102
+
103
+ A :class:`._Dispatch` class is generated for each :class:`.Events`
104
+ class defined, by the :meth:`._HasEventsDispatch._create_dispatcher_class`
105
+ method. The original :class:`.Events` classes remain untouched.
106
+ This decouples the construction of :class:`.Events` subclasses from
107
+ the implementation used by the event internals, and allows
108
+ inspecting tools like Sphinx to work in an unsurprising
109
+ way against the public API.
110
+
111
+ """
112
+
113
+ # "active_history" is an ORM case we add here. ideally a better
114
+ # system would be in place for ad-hoc attributes.
115
+ __slots__ = "_parent", "_instance_cls", "__dict__", "_empty_listeners"
116
+
117
+ _active_history: bool
118
+
119
+ _empty_listener_reg: MutableMapping[
120
+ Type[_ET], Dict[str, _EmptyListener[_ET]]
121
+ ] = weakref.WeakKeyDictionary()
122
+
123
+ _empty_listeners: Dict[str, _EmptyListener[_ET]]
124
+
125
+ _event_names: List[str]
126
+
127
+ _instance_cls: Optional[Type[_ET]]
128
+
129
+ _joined_dispatch_cls: Type[_JoinedDispatcher[_ET]]
130
+
131
+ _events: Type[_HasEventsDispatch[_ET]]
132
+ """reference back to the Events class.
133
+
134
+ Bidirectional against _HasEventsDispatch.dispatch
135
+
136
+ """
137
+
138
+ def __init__(
139
+ self,
140
+ parent: Optional[_Dispatch[_ET]],
141
+ instance_cls: Optional[Type[_ET]] = None,
142
+ ):
143
+ self._parent = parent
144
+ self._instance_cls = instance_cls
145
+
146
+ if instance_cls:
147
+ assert parent is not None
148
+ try:
149
+ self._empty_listeners = self._empty_listener_reg[instance_cls]
150
+ except KeyError:
151
+ self._empty_listeners = self._empty_listener_reg[
152
+ instance_cls
153
+ ] = {
154
+ ls.name: _EmptyListener(ls, instance_cls)
155
+ for ls in parent._event_descriptors
156
+ }
157
+ else:
158
+ self._empty_listeners = {}
159
+
160
+ def __getattr__(self, name: str) -> _InstanceLevelDispatch[_ET]:
161
+ # Assign EmptyListeners as attributes on demand
162
+ # to reduce startup time for new dispatch objects.
163
+ try:
164
+ ls = self._empty_listeners[name]
165
+ except KeyError:
166
+ raise AttributeError(name)
167
+ else:
168
+ setattr(self, ls.name, ls)
169
+ return ls
170
+
171
+ @property
172
+ def _event_descriptors(self) -> Iterator[_ClsLevelDispatch[_ET]]:
173
+ for k in self._event_names:
174
+ # Yield _ClsLevelDispatch related
175
+ # to relevant event name.
176
+ yield getattr(self, k)
177
+
178
+ def _listen(self, event_key: _EventKey[_ET], **kw: Any) -> None:
179
+ return self._events._listen(event_key, **kw)
180
+
181
+ def _for_class(self, instance_cls: Type[_ET]) -> _Dispatch[_ET]:
182
+ return self.__class__(self, instance_cls)
183
+
184
+ def _for_instance(self, instance: _ET) -> _Dispatch[_ET]:
185
+ instance_cls = instance.__class__
186
+ return self._for_class(instance_cls)
187
+
188
+ def _join(self, other: _DispatchCommon[_ET]) -> _JoinedDispatcher[_ET]:
189
+ """Create a 'join' of this :class:`._Dispatch` and another.
190
+
191
+ This new dispatcher will dispatch events to both
192
+ :class:`._Dispatch` objects.
193
+
194
+ """
195
+ assert "_joined_dispatch_cls" in self.__class__.__dict__
196
+
197
+ return self._joined_dispatch_cls(self, other)
198
+
199
+ def __reduce__(self) -> Union[str, Tuple[Any, ...]]:
200
+ return _UnpickleDispatch(), (self._instance_cls,)
201
+
202
+ def _update(
203
+ self, other: _Dispatch[_ET], only_propagate: bool = True
204
+ ) -> None:
205
+ """Populate from the listeners in another :class:`_Dispatch`
206
+ object."""
207
+ for ls in other._event_descriptors:
208
+ if isinstance(ls, _EmptyListener):
209
+ continue
210
+ getattr(self, ls.name).for_modify(self)._update(
211
+ ls, only_propagate=only_propagate
212
+ )
213
+
214
+ def _clear(self) -> None:
215
+ for ls in self._event_descriptors:
216
+ ls.for_modify(self).clear()
217
+
218
+
219
+ def _remove_dispatcher(cls: Type[_HasEventsDispatch[_ET]]) -> None:
220
+ for k in cls.dispatch._event_names:
221
+ _registrars[k].remove(cls)
222
+ if not _registrars[k]:
223
+ del _registrars[k]
224
+
225
+
226
+ class _HasEventsDispatch(Generic[_ET]):
227
+ _dispatch_target: Optional[Type[_ET]]
228
+ """class which will receive the .dispatch collection"""
229
+
230
+ dispatch: _Dispatch[_ET]
231
+ """reference back to the _Dispatch class.
232
+
233
+ Bidirectional against _Dispatch._events
234
+
235
+ """
236
+
237
+ if typing.TYPE_CHECKING:
238
+
239
+ def __getattr__(self, name: str) -> _InstanceLevelDispatch[_ET]: ...
240
+
241
+ def __init_subclass__(cls) -> None:
242
+ """Intercept new Event subclasses and create associated _Dispatch
243
+ classes."""
244
+
245
+ cls._create_dispatcher_class(cls.__name__, cls.__bases__, cls.__dict__)
246
+
247
+ @classmethod
248
+ def _accept_with(
249
+ cls, target: Union[_ET, Type[_ET]], identifier: str
250
+ ) -> Optional[Union[_ET, Type[_ET]]]:
251
+ raise NotImplementedError()
252
+
253
+ @classmethod
254
+ def _listen(
255
+ cls,
256
+ event_key: _EventKey[_ET],
257
+ *,
258
+ propagate: bool = False,
259
+ insert: bool = False,
260
+ named: bool = False,
261
+ asyncio: bool = False,
262
+ ) -> None:
263
+ raise NotImplementedError()
264
+
265
+ @staticmethod
266
+ def _set_dispatch(
267
+ klass: Type[_HasEventsDispatch[_ET]],
268
+ dispatch_cls: Type[_Dispatch[_ET]],
269
+ ) -> _Dispatch[_ET]:
270
+ # This allows an Events subclass to define additional utility
271
+ # methods made available to the target via
272
+ # "self.dispatch._events.<utilitymethod>"
273
+ # @staticmethod to allow easy "super" calls while in a metaclass
274
+ # constructor.
275
+ klass.dispatch = dispatch_cls(None)
276
+ dispatch_cls._events = klass
277
+ return klass.dispatch
278
+
279
+ @classmethod
280
+ def _create_dispatcher_class(
281
+ cls, classname: str, bases: Tuple[type, ...], dict_: Mapping[str, Any]
282
+ ) -> None:
283
+ """Create a :class:`._Dispatch` class corresponding to an
284
+ :class:`.Events` class."""
285
+
286
+ # there's all kinds of ways to do this,
287
+ # i.e. make a Dispatch class that shares the '_listen' method
288
+ # of the Event class, this is the straight monkeypatch.
289
+ if hasattr(cls, "dispatch"):
290
+ dispatch_base = cls.dispatch.__class__
291
+ else:
292
+ dispatch_base = _Dispatch
293
+
294
+ event_names = [k for k in dict_ if _is_event_name(k)]
295
+ dispatch_cls = cast(
296
+ "Type[_Dispatch[_ET]]",
297
+ type(
298
+ "%sDispatch" % classname,
299
+ (dispatch_base,),
300
+ {"__slots__": event_names},
301
+ ),
302
+ )
303
+
304
+ dispatch_cls._event_names = event_names
305
+ dispatch_inst = cls._set_dispatch(cls, dispatch_cls)
306
+ for k in dispatch_cls._event_names:
307
+ setattr(dispatch_inst, k, _ClsLevelDispatch(cls, dict_[k]))
308
+ _registrars[k].append(cls)
309
+
310
+ for super_ in dispatch_cls.__bases__:
311
+ if issubclass(super_, _Dispatch) and super_ is not _Dispatch:
312
+ for ls in super_._events.dispatch._event_descriptors:
313
+ setattr(dispatch_inst, ls.name, ls)
314
+ dispatch_cls._event_names.append(ls.name)
315
+
316
+ if getattr(cls, "_dispatch_target", None):
317
+ dispatch_target_cls = cls._dispatch_target
318
+ assert dispatch_target_cls is not None
319
+ if (
320
+ hasattr(dispatch_target_cls, "__slots__")
321
+ and "_slots_dispatch" in dispatch_target_cls.__slots__
322
+ ):
323
+ dispatch_target_cls.dispatch = slots_dispatcher(cls)
324
+ else:
325
+ dispatch_target_cls.dispatch = dispatcher(cls)
326
+
327
+ klass = type(
328
+ "Joined%s" % dispatch_cls.__name__,
329
+ (_JoinedDispatcher,),
330
+ {"__slots__": event_names},
331
+ )
332
+ dispatch_cls._joined_dispatch_cls = klass
333
+
334
+ # establish pickle capability by adding it to this module
335
+ globals()[klass.__name__] = klass
336
+
337
+
338
+ class _JoinedDispatcher(_DispatchCommon[_ET]):
339
+ """Represent a connection between two _Dispatch objects."""
340
+
341
+ __slots__ = "local", "parent", "_instance_cls"
342
+
343
+ local: _DispatchCommon[_ET]
344
+ parent: _DispatchCommon[_ET]
345
+ _instance_cls: Optional[Type[_ET]]
346
+
347
+ def __init__(
348
+ self, local: _DispatchCommon[_ET], parent: _DispatchCommon[_ET]
349
+ ):
350
+ self.local = local
351
+ self.parent = parent
352
+ self._instance_cls = self.local._instance_cls
353
+
354
+ def __reduce__(self) -> Any:
355
+ return (self.__class__, (self.local, self.parent))
356
+
357
+ def __getattr__(self, name: str) -> _JoinedListener[_ET]:
358
+ # Assign _JoinedListeners as attributes on demand
359
+ # to reduce startup time for new dispatch objects.
360
+ ls = getattr(self.local, name)
361
+ jl = _JoinedListener(self.parent, ls.name, ls)
362
+ setattr(self, ls.name, jl)
363
+ return jl
364
+
365
+ def _listen(self, event_key: _EventKey[_ET], **kw: Any) -> None:
366
+ return self.parent._listen(event_key, **kw)
367
+
368
+ @property
369
+ def _events(self) -> Type[_HasEventsDispatch[_ET]]:
370
+ return self.parent._events
371
+
372
+
373
+ class Events(_HasEventsDispatch[_ET]):
374
+ """Define event listening functions for a particular target type."""
375
+
376
+ @classmethod
377
+ def _accept_with(
378
+ cls, target: Union[_ET, Type[_ET]], identifier: str
379
+ ) -> Optional[Union[_ET, Type[_ET]]]:
380
+ def dispatch_is(*types: Type[Any]) -> bool:
381
+ return all(isinstance(target.dispatch, t) for t in types)
382
+
383
+ def dispatch_parent_is(t: Type[Any]) -> bool:
384
+ parent = cast("_JoinedDispatcher[_ET]", target.dispatch).parent
385
+ while isinstance(parent, _JoinedDispatcher):
386
+ parent = cast("_JoinedDispatcher[_ET]", parent).parent
387
+
388
+ return isinstance(parent, t)
389
+
390
+ # Mapper, ClassManager, Session override this to
391
+ # also accept classes, scoped_sessions, sessionmakers, etc.
392
+ if hasattr(target, "dispatch"):
393
+ if (
394
+ dispatch_is(cls.dispatch.__class__)
395
+ or dispatch_is(type, cls.dispatch.__class__)
396
+ or (
397
+ dispatch_is(_JoinedDispatcher)
398
+ and dispatch_parent_is(cls.dispatch.__class__)
399
+ )
400
+ ):
401
+ return target
402
+
403
+ return None
404
+
405
+ @classmethod
406
+ def _listen(
407
+ cls,
408
+ event_key: _EventKey[_ET],
409
+ *,
410
+ propagate: bool = False,
411
+ insert: bool = False,
412
+ named: bool = False,
413
+ asyncio: bool = False,
414
+ ) -> None:
415
+ event_key.base_listen(
416
+ propagate=propagate, insert=insert, named=named, asyncio=asyncio
417
+ )
418
+
419
+ @classmethod
420
+ def _remove(cls, event_key: _EventKey[_ET]) -> None:
421
+ event_key.remove()
422
+
423
+ @classmethod
424
+ def _clear(cls) -> None:
425
+ cls.dispatch._clear()
426
+
427
+
428
+ class dispatcher(Generic[_ET]):
429
+ """Descriptor used by target classes to
430
+ deliver the _Dispatch class at the class level
431
+ and produce new _Dispatch instances for target
432
+ instances.
433
+
434
+ """
435
+
436
+ def __init__(self, events: Type[_HasEventsDispatch[_ET]]):
437
+ self.dispatch = events.dispatch
438
+ self.events = events
439
+
440
+ @overload
441
+ def __get__(
442
+ self, obj: Literal[None], cls: Type[Any]
443
+ ) -> Type[_Dispatch[_ET]]: ...
444
+
445
+ @overload
446
+ def __get__(self, obj: Any, cls: Type[Any]) -> _DispatchCommon[_ET]: ...
447
+
448
+ def __get__(self, obj: Any, cls: Type[Any]) -> Any:
449
+ if obj is None:
450
+ return self.dispatch
451
+
452
+ disp = self.dispatch._for_instance(obj)
453
+ try:
454
+ obj.__dict__["dispatch"] = disp
455
+ except AttributeError as ae:
456
+ raise TypeError(
457
+ "target %r doesn't have __dict__, should it be "
458
+ "defining _slots_dispatch?" % (obj,)
459
+ ) from ae
460
+ return disp
461
+
462
+
463
+ class slots_dispatcher(dispatcher[_ET]):
464
+ def __get__(self, obj: Any, cls: Type[Any]) -> Any:
465
+ if obj is None:
466
+ return self.dispatch
467
+
468
+ if hasattr(obj, "_slots_dispatch"):
469
+ return obj._slots_dispatch
470
+
471
+ disp = self.dispatch._for_instance(obj)
472
+ obj._slots_dispatch = disp
473
+ return disp