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,2013 @@
1
+ # ext/associationproxy.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
+
8
+ """Contain the ``AssociationProxy`` class.
9
+
10
+ The ``AssociationProxy`` is a Python property object which provides
11
+ transparent proxied access to the endpoint of an association object.
12
+
13
+ See the example ``examples/association/proxied_association.py``.
14
+
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import operator
19
+ import typing
20
+ from typing import AbstractSet
21
+ from typing import Any
22
+ from typing import Callable
23
+ from typing import cast
24
+ from typing import Collection
25
+ from typing import Dict
26
+ from typing import Generic
27
+ from typing import ItemsView
28
+ from typing import Iterable
29
+ from typing import Iterator
30
+ from typing import KeysView
31
+ from typing import List
32
+ from typing import Mapping
33
+ from typing import MutableMapping
34
+ from typing import MutableSequence
35
+ from typing import MutableSet
36
+ from typing import NoReturn
37
+ from typing import Optional
38
+ from typing import overload
39
+ from typing import Set
40
+ from typing import Tuple
41
+ from typing import Type
42
+ from typing import TypeVar
43
+ from typing import Union
44
+ from typing import ValuesView
45
+
46
+ from .. import ColumnElement
47
+ from .. import exc
48
+ from .. import inspect
49
+ from .. import orm
50
+ from .. import util
51
+ from ..orm import collections
52
+ from ..orm import InspectionAttrExtensionType
53
+ from ..orm import interfaces
54
+ from ..orm import ORMDescriptor
55
+ from ..orm.base import SQLORMOperations
56
+ from ..orm.interfaces import _AttributeOptions
57
+ from ..orm.interfaces import _DCAttributeOptions
58
+ from ..orm.interfaces import _DEFAULT_ATTRIBUTE_OPTIONS
59
+ from ..sql import operators
60
+ from ..sql import or_
61
+ from ..sql.base import _NoArg
62
+ from ..util.typing import Literal
63
+ from ..util.typing import Protocol
64
+ from ..util.typing import Self
65
+ from ..util.typing import SupportsIndex
66
+ from ..util.typing import SupportsKeysAndGetItem
67
+
68
+ if typing.TYPE_CHECKING:
69
+ from ..orm.interfaces import MapperProperty
70
+ from ..orm.interfaces import PropComparator
71
+ from ..orm.mapper import Mapper
72
+ from ..sql._typing import _ColumnExpressionArgument
73
+ from ..sql._typing import _InfoType
74
+
75
+
76
+ _T = TypeVar("_T", bound=Any)
77
+ _T_co = TypeVar("_T_co", bound=Any, covariant=True)
78
+ _T_con = TypeVar("_T_con", bound=Any, contravariant=True)
79
+ _S = TypeVar("_S", bound=Any)
80
+ _KT = TypeVar("_KT", bound=Any)
81
+ _VT = TypeVar("_VT", bound=Any)
82
+
83
+
84
+ def association_proxy(
85
+ target_collection: str,
86
+ attr: str,
87
+ *,
88
+ creator: Optional[_CreatorProtocol] = None,
89
+ getset_factory: Optional[_GetSetFactoryProtocol] = None,
90
+ proxy_factory: Optional[_ProxyFactoryProtocol] = None,
91
+ proxy_bulk_set: Optional[_ProxyBulkSetProtocol] = None,
92
+ info: Optional[_InfoType] = None,
93
+ cascade_scalar_deletes: bool = False,
94
+ create_on_none_assignment: bool = False,
95
+ init: Union[_NoArg, bool] = _NoArg.NO_ARG,
96
+ repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002
97
+ default: Optional[Any] = _NoArg.NO_ARG,
98
+ default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG,
99
+ compare: Union[_NoArg, bool] = _NoArg.NO_ARG,
100
+ kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG,
101
+ hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002
102
+ ) -> AssociationProxy[Any]:
103
+ r"""Return a Python property implementing a view of a target
104
+ attribute which references an attribute on members of the
105
+ target.
106
+
107
+ The returned value is an instance of :class:`.AssociationProxy`.
108
+
109
+ Implements a Python property representing a relationship as a collection
110
+ of simpler values, or a scalar value. The proxied property will mimic
111
+ the collection type of the target (list, dict or set), or, in the case of
112
+ a one to one relationship, a simple scalar value.
113
+
114
+ :param target_collection: Name of the attribute that is the immediate
115
+ target. This attribute is typically mapped by
116
+ :func:`~sqlalchemy.orm.relationship` to link to a target collection, but
117
+ can also be a many-to-one or non-scalar relationship.
118
+
119
+ :param attr: Attribute on the associated instance or instances that
120
+ are available on instances of the target object.
121
+
122
+ :param creator: optional.
123
+
124
+ Defines custom behavior when new items are added to the proxied
125
+ collection.
126
+
127
+ By default, adding new items to the collection will trigger a
128
+ construction of an instance of the target object, passing the given
129
+ item as a positional argument to the target constructor. For cases
130
+ where this isn't sufficient, :paramref:`.association_proxy.creator`
131
+ can supply a callable that will construct the object in the
132
+ appropriate way, given the item that was passed.
133
+
134
+ For list- and set- oriented collections, a single argument is
135
+ passed to the callable. For dictionary oriented collections, two
136
+ arguments are passed, corresponding to the key and value.
137
+
138
+ The :paramref:`.association_proxy.creator` callable is also invoked
139
+ for scalar (i.e. many-to-one, one-to-one) relationships. If the
140
+ current value of the target relationship attribute is ``None``, the
141
+ callable is used to construct a new object. If an object value already
142
+ exists, the given attribute value is populated onto that object.
143
+
144
+ .. seealso::
145
+
146
+ :ref:`associationproxy_creator`
147
+
148
+ :param cascade_scalar_deletes: when True, indicates that setting
149
+ the proxied value to ``None``, or deleting it via ``del``, should
150
+ also remove the source object. Only applies to scalar attributes.
151
+ Normally, removing the proxied target will not remove the proxy
152
+ source, as this object may have other state that is still to be
153
+ kept.
154
+
155
+ .. versionadded:: 1.3
156
+
157
+ .. seealso::
158
+
159
+ :ref:`cascade_scalar_deletes` - complete usage example
160
+
161
+ :param create_on_none_assignment: when True, indicates that setting
162
+ the proxied value to ``None`` should **create** the source object
163
+ if it does not exist, using the creator. Only applies to scalar
164
+ attributes. This is mutually exclusive
165
+ vs. the :paramref:`.assocation_proxy.cascade_scalar_deletes`.
166
+
167
+ .. versionadded:: 2.0.18
168
+
169
+ :param init: Specific to :ref:`orm_declarative_native_dataclasses`,
170
+ specifies if the mapped attribute should be part of the ``__init__()``
171
+ method as generated by the dataclass process.
172
+
173
+ .. versionadded:: 2.0.0b4
174
+
175
+ :param repr: Specific to :ref:`orm_declarative_native_dataclasses`,
176
+ specifies if the attribute established by this :class:`.AssociationProxy`
177
+ should be part of the ``__repr__()`` method as generated by the dataclass
178
+ process.
179
+
180
+ .. versionadded:: 2.0.0b4
181
+
182
+ :param default_factory: Specific to
183
+ :ref:`orm_declarative_native_dataclasses`, specifies a default-value
184
+ generation function that will take place as part of the ``__init__()``
185
+ method as generated by the dataclass process.
186
+
187
+ .. versionadded:: 2.0.0b4
188
+
189
+ :param compare: Specific to
190
+ :ref:`orm_declarative_native_dataclasses`, indicates if this field
191
+ should be included in comparison operations when generating the
192
+ ``__eq__()`` and ``__ne__()`` methods for the mapped class.
193
+
194
+ .. versionadded:: 2.0.0b4
195
+
196
+ :param kw_only: Specific to :ref:`orm_declarative_native_dataclasses`,
197
+ indicates if this field should be marked as keyword-only when generating
198
+ the ``__init__()`` method as generated by the dataclass process.
199
+
200
+ .. versionadded:: 2.0.0b4
201
+
202
+ :param hash: Specific to
203
+ :ref:`orm_declarative_native_dataclasses`, controls if this field
204
+ is included when generating the ``__hash__()`` method for the mapped
205
+ class.
206
+
207
+ .. versionadded:: 2.0.36
208
+
209
+ :param info: optional, will be assigned to
210
+ :attr:`.AssociationProxy.info` if present.
211
+
212
+
213
+ The following additional parameters involve injection of custom behaviors
214
+ within the :class:`.AssociationProxy` object and are for advanced use
215
+ only:
216
+
217
+ :param getset_factory: Optional. Proxied attribute access is
218
+ automatically handled by routines that get and set values based on
219
+ the `attr` argument for this proxy.
220
+
221
+ If you would like to customize this behavior, you may supply a
222
+ `getset_factory` callable that produces a tuple of `getter` and
223
+ `setter` functions. The factory is called with two arguments, the
224
+ abstract type of the underlying collection and this proxy instance.
225
+
226
+ :param proxy_factory: Optional. The type of collection to emulate is
227
+ determined by sniffing the target collection. If your collection
228
+ type can't be determined by duck typing or you'd like to use a
229
+ different collection implementation, you may supply a factory
230
+ function to produce those collections. Only applicable to
231
+ non-scalar relationships.
232
+
233
+ :param proxy_bulk_set: Optional, use with proxy_factory.
234
+
235
+
236
+ """
237
+ return AssociationProxy(
238
+ target_collection,
239
+ attr,
240
+ creator=creator,
241
+ getset_factory=getset_factory,
242
+ proxy_factory=proxy_factory,
243
+ proxy_bulk_set=proxy_bulk_set,
244
+ info=info,
245
+ cascade_scalar_deletes=cascade_scalar_deletes,
246
+ create_on_none_assignment=create_on_none_assignment,
247
+ attribute_options=_AttributeOptions(
248
+ init, repr, default, default_factory, compare, kw_only, hash
249
+ ),
250
+ )
251
+
252
+
253
+ class AssociationProxyExtensionType(InspectionAttrExtensionType):
254
+ ASSOCIATION_PROXY = "ASSOCIATION_PROXY"
255
+ """Symbol indicating an :class:`.InspectionAttr` that's
256
+ of type :class:`.AssociationProxy`.
257
+
258
+ Is assigned to the :attr:`.InspectionAttr.extension_type`
259
+ attribute.
260
+
261
+ """
262
+
263
+
264
+ class _GetterProtocol(Protocol[_T_co]):
265
+ def __call__(self, instance: Any) -> _T_co: ...
266
+
267
+
268
+ # mypy 0.990 we are no longer allowed to make this Protocol[_T_con]
269
+ class _SetterProtocol(Protocol): ...
270
+
271
+
272
+ class _PlainSetterProtocol(_SetterProtocol, Protocol[_T_con]):
273
+ def __call__(self, instance: Any, value: _T_con) -> None: ...
274
+
275
+
276
+ class _DictSetterProtocol(_SetterProtocol, Protocol[_T_con]):
277
+ def __call__(self, instance: Any, key: Any, value: _T_con) -> None: ...
278
+
279
+
280
+ # mypy 0.990 we are no longer allowed to make this Protocol[_T_con]
281
+ class _CreatorProtocol(Protocol): ...
282
+
283
+
284
+ class _PlainCreatorProtocol(_CreatorProtocol, Protocol[_T_con]):
285
+ def __call__(self, value: _T_con) -> Any: ...
286
+
287
+
288
+ class _KeyCreatorProtocol(_CreatorProtocol, Protocol[_T_con]):
289
+ def __call__(self, key: Any, value: Optional[_T_con]) -> Any: ...
290
+
291
+
292
+ class _LazyCollectionProtocol(Protocol[_T]):
293
+ def __call__(
294
+ self,
295
+ ) -> Union[
296
+ MutableSet[_T], MutableMapping[Any, _T], MutableSequence[_T]
297
+ ]: ...
298
+
299
+
300
+ class _GetSetFactoryProtocol(Protocol):
301
+ def __call__(
302
+ self,
303
+ collection_class: Optional[Type[Any]],
304
+ assoc_instance: AssociationProxyInstance[Any],
305
+ ) -> Tuple[_GetterProtocol[Any], _SetterProtocol]: ...
306
+
307
+
308
+ class _ProxyFactoryProtocol(Protocol):
309
+ def __call__(
310
+ self,
311
+ lazy_collection: _LazyCollectionProtocol[Any],
312
+ creator: _CreatorProtocol,
313
+ value_attr: str,
314
+ parent: AssociationProxyInstance[Any],
315
+ ) -> Any: ...
316
+
317
+
318
+ class _ProxyBulkSetProtocol(Protocol):
319
+ def __call__(
320
+ self, proxy: _AssociationCollection[Any], collection: Iterable[Any]
321
+ ) -> None: ...
322
+
323
+
324
+ class _AssociationProxyProtocol(Protocol[_T]):
325
+ """describes the interface of :class:`.AssociationProxy`
326
+ without including descriptor methods in the interface."""
327
+
328
+ creator: Optional[_CreatorProtocol]
329
+ key: str
330
+ target_collection: str
331
+ value_attr: str
332
+ cascade_scalar_deletes: bool
333
+ create_on_none_assignment: bool
334
+ getset_factory: Optional[_GetSetFactoryProtocol]
335
+ proxy_factory: Optional[_ProxyFactoryProtocol]
336
+ proxy_bulk_set: Optional[_ProxyBulkSetProtocol]
337
+
338
+ @util.ro_memoized_property
339
+ def info(self) -> _InfoType: ...
340
+
341
+ def for_class(
342
+ self, class_: Type[Any], obj: Optional[object] = None
343
+ ) -> AssociationProxyInstance[_T]: ...
344
+
345
+ def _default_getset(
346
+ self, collection_class: Any
347
+ ) -> Tuple[_GetterProtocol[Any], _SetterProtocol]: ...
348
+
349
+
350
+ class AssociationProxy(
351
+ interfaces.InspectionAttrInfo,
352
+ ORMDescriptor[_T],
353
+ _DCAttributeOptions,
354
+ _AssociationProxyProtocol[_T],
355
+ ):
356
+ """A descriptor that presents a read/write view of an object attribute."""
357
+
358
+ is_attribute = True
359
+ extension_type = AssociationProxyExtensionType.ASSOCIATION_PROXY
360
+
361
+ def __init__(
362
+ self,
363
+ target_collection: str,
364
+ attr: str,
365
+ *,
366
+ creator: Optional[_CreatorProtocol] = None,
367
+ getset_factory: Optional[_GetSetFactoryProtocol] = None,
368
+ proxy_factory: Optional[_ProxyFactoryProtocol] = None,
369
+ proxy_bulk_set: Optional[_ProxyBulkSetProtocol] = None,
370
+ info: Optional[_InfoType] = None,
371
+ cascade_scalar_deletes: bool = False,
372
+ create_on_none_assignment: bool = False,
373
+ attribute_options: Optional[_AttributeOptions] = None,
374
+ ):
375
+ """Construct a new :class:`.AssociationProxy`.
376
+
377
+ The :class:`.AssociationProxy` object is typically constructed using
378
+ the :func:`.association_proxy` constructor function. See the
379
+ description of :func:`.association_proxy` for a description of all
380
+ parameters.
381
+
382
+
383
+ """
384
+ self.target_collection = target_collection
385
+ self.value_attr = attr
386
+ self.creator = creator
387
+ self.getset_factory = getset_factory
388
+ self.proxy_factory = proxy_factory
389
+ self.proxy_bulk_set = proxy_bulk_set
390
+
391
+ if cascade_scalar_deletes and create_on_none_assignment:
392
+ raise exc.ArgumentError(
393
+ "The cascade_scalar_deletes and create_on_none_assignment "
394
+ "parameters are mutually exclusive."
395
+ )
396
+ self.cascade_scalar_deletes = cascade_scalar_deletes
397
+ self.create_on_none_assignment = create_on_none_assignment
398
+
399
+ self.key = "_%s_%s_%s" % (
400
+ type(self).__name__,
401
+ target_collection,
402
+ id(self),
403
+ )
404
+ if info:
405
+ self.info = info # type: ignore
406
+
407
+ if (
408
+ attribute_options
409
+ and attribute_options != _DEFAULT_ATTRIBUTE_OPTIONS
410
+ ):
411
+ self._has_dataclass_arguments = True
412
+ self._attribute_options = attribute_options
413
+ else:
414
+ self._has_dataclass_arguments = False
415
+ self._attribute_options = _DEFAULT_ATTRIBUTE_OPTIONS
416
+
417
+ @overload
418
+ def __get__(
419
+ self, instance: Literal[None], owner: Literal[None]
420
+ ) -> Self: ...
421
+
422
+ @overload
423
+ def __get__(
424
+ self, instance: Literal[None], owner: Any
425
+ ) -> AssociationProxyInstance[_T]: ...
426
+
427
+ @overload
428
+ def __get__(self, instance: object, owner: Any) -> _T: ...
429
+
430
+ def __get__(
431
+ self, instance: object, owner: Any
432
+ ) -> Union[AssociationProxyInstance[_T], _T, AssociationProxy[_T]]:
433
+ if owner is None:
434
+ return self
435
+ inst = self._as_instance(owner, instance)
436
+ if inst:
437
+ return inst.get(instance)
438
+
439
+ assert instance is None
440
+
441
+ return self
442
+
443
+ def __set__(self, instance: object, values: _T) -> None:
444
+ class_ = type(instance)
445
+ self._as_instance(class_, instance).set(instance, values)
446
+
447
+ def __delete__(self, instance: object) -> None:
448
+ class_ = type(instance)
449
+ self._as_instance(class_, instance).delete(instance)
450
+
451
+ def for_class(
452
+ self, class_: Type[Any], obj: Optional[object] = None
453
+ ) -> AssociationProxyInstance[_T]:
454
+ r"""Return the internal state local to a specific mapped class.
455
+
456
+ E.g., given a class ``User``::
457
+
458
+ class User(Base):
459
+ # ...
460
+
461
+ keywords = association_proxy('kws', 'keyword')
462
+
463
+ If we access this :class:`.AssociationProxy` from
464
+ :attr:`_orm.Mapper.all_orm_descriptors`, and we want to view the
465
+ target class for this proxy as mapped by ``User``::
466
+
467
+ inspect(User).all_orm_descriptors["keywords"].for_class(User).target_class
468
+
469
+ This returns an instance of :class:`.AssociationProxyInstance` that
470
+ is specific to the ``User`` class. The :class:`.AssociationProxy`
471
+ object remains agnostic of its parent class.
472
+
473
+ :param class\_: the class that we are returning state for.
474
+
475
+ :param obj: optional, an instance of the class that is required
476
+ if the attribute refers to a polymorphic target, e.g. where we have
477
+ to look at the type of the actual destination object to get the
478
+ complete path.
479
+
480
+ .. versionadded:: 1.3 - :class:`.AssociationProxy` no longer stores
481
+ any state specific to a particular parent class; the state is now
482
+ stored in per-class :class:`.AssociationProxyInstance` objects.
483
+
484
+
485
+ """
486
+ return self._as_instance(class_, obj)
487
+
488
+ def _as_instance(
489
+ self, class_: Any, obj: Any
490
+ ) -> AssociationProxyInstance[_T]:
491
+ try:
492
+ inst = class_.__dict__[self.key + "_inst"]
493
+ except KeyError:
494
+ inst = None
495
+
496
+ # avoid exception context
497
+ if inst is None:
498
+ owner = self._calc_owner(class_)
499
+ if owner is not None:
500
+ inst = AssociationProxyInstance.for_proxy(self, owner, obj)
501
+ setattr(class_, self.key + "_inst", inst)
502
+ else:
503
+ inst = None
504
+
505
+ if inst is not None and not inst._is_canonical:
506
+ # the AssociationProxyInstance can't be generalized
507
+ # since the proxied attribute is not on the targeted
508
+ # class, only on subclasses of it, which might be
509
+ # different. only return for the specific
510
+ # object's current value
511
+ return inst._non_canonical_get_for_object(obj) # type: ignore
512
+ else:
513
+ return inst # type: ignore # TODO
514
+
515
+ def _calc_owner(self, target_cls: Any) -> Any:
516
+ # we might be getting invoked for a subclass
517
+ # that is not mapped yet, in some declarative situations.
518
+ # save until we are mapped
519
+ try:
520
+ insp = inspect(target_cls)
521
+ except exc.NoInspectionAvailable:
522
+ # can't find a mapper, don't set owner. if we are a not-yet-mapped
523
+ # subclass, we can also scan through __mro__ to find a mapped
524
+ # class, but instead just wait for us to be called again against a
525
+ # mapped class normally.
526
+ return None
527
+ else:
528
+ return insp.mapper.class_manager.class_
529
+
530
+ def _default_getset(
531
+ self, collection_class: Any
532
+ ) -> Tuple[_GetterProtocol[Any], _SetterProtocol]:
533
+ attr = self.value_attr
534
+ _getter = operator.attrgetter(attr)
535
+
536
+ def getter(instance: Any) -> Optional[Any]:
537
+ return _getter(instance) if instance is not None else None
538
+
539
+ if collection_class is dict:
540
+
541
+ def dict_setter(instance: Any, k: Any, value: Any) -> None:
542
+ setattr(instance, attr, value)
543
+
544
+ return getter, dict_setter
545
+
546
+ else:
547
+
548
+ def plain_setter(o: Any, v: Any) -> None:
549
+ setattr(o, attr, v)
550
+
551
+ return getter, plain_setter
552
+
553
+ def __repr__(self) -> str:
554
+ return "AssociationProxy(%r, %r)" % (
555
+ self.target_collection,
556
+ self.value_attr,
557
+ )
558
+
559
+
560
+ # the pep-673 Self type does not work in Mypy for a "hybrid"
561
+ # style method that returns type or Self, so for one specific case
562
+ # we still need to use the pre-pep-673 workaround.
563
+ _Self = TypeVar("_Self", bound="AssociationProxyInstance[Any]")
564
+
565
+
566
+ class AssociationProxyInstance(SQLORMOperations[_T]):
567
+ """A per-class object that serves class- and object-specific results.
568
+
569
+ This is used by :class:`.AssociationProxy` when it is invoked
570
+ in terms of a specific class or instance of a class, i.e. when it is
571
+ used as a regular Python descriptor.
572
+
573
+ When referring to the :class:`.AssociationProxy` as a normal Python
574
+ descriptor, the :class:`.AssociationProxyInstance` is the object that
575
+ actually serves the information. Under normal circumstances, its presence
576
+ is transparent::
577
+
578
+ >>> User.keywords.scalar
579
+ False
580
+
581
+ In the special case that the :class:`.AssociationProxy` object is being
582
+ accessed directly, in order to get an explicit handle to the
583
+ :class:`.AssociationProxyInstance`, use the
584
+ :meth:`.AssociationProxy.for_class` method::
585
+
586
+ proxy_state = inspect(User).all_orm_descriptors["keywords"].for_class(User)
587
+
588
+ # view if proxy object is scalar or not
589
+ >>> proxy_state.scalar
590
+ False
591
+
592
+ .. versionadded:: 1.3
593
+
594
+ """ # noqa
595
+
596
+ collection_class: Optional[Type[Any]]
597
+ parent: _AssociationProxyProtocol[_T]
598
+
599
+ def __init__(
600
+ self,
601
+ parent: _AssociationProxyProtocol[_T],
602
+ owning_class: Type[Any],
603
+ target_class: Type[Any],
604
+ value_attr: str,
605
+ ):
606
+ self.parent = parent
607
+ self.key = parent.key
608
+ self.owning_class = owning_class
609
+ self.target_collection = parent.target_collection
610
+ self.collection_class = None
611
+ self.target_class = target_class
612
+ self.value_attr = value_attr
613
+
614
+ target_class: Type[Any]
615
+ """The intermediary class handled by this
616
+ :class:`.AssociationProxyInstance`.
617
+
618
+ Intercepted append/set/assignment events will result
619
+ in the generation of new instances of this class.
620
+
621
+ """
622
+
623
+ @classmethod
624
+ def for_proxy(
625
+ cls,
626
+ parent: AssociationProxy[_T],
627
+ owning_class: Type[Any],
628
+ parent_instance: Any,
629
+ ) -> AssociationProxyInstance[_T]:
630
+ target_collection = parent.target_collection
631
+ value_attr = parent.value_attr
632
+ prop = cast(
633
+ "orm.RelationshipProperty[_T]",
634
+ orm.class_mapper(owning_class).get_property(target_collection),
635
+ )
636
+
637
+ # this was never asserted before but this should be made clear.
638
+ if not isinstance(prop, orm.RelationshipProperty):
639
+ raise NotImplementedError(
640
+ "association proxy to a non-relationship "
641
+ "intermediary is not supported"
642
+ ) from None
643
+
644
+ target_class = prop.mapper.class_
645
+
646
+ try:
647
+ target_assoc = cast(
648
+ "AssociationProxyInstance[_T]",
649
+ cls._cls_unwrap_target_assoc_proxy(target_class, value_attr),
650
+ )
651
+ except AttributeError:
652
+ # the proxied attribute doesn't exist on the target class;
653
+ # return an "ambiguous" instance that will work on a per-object
654
+ # basis
655
+ return AmbiguousAssociationProxyInstance(
656
+ parent, owning_class, target_class, value_attr
657
+ )
658
+ except Exception as err:
659
+ raise exc.InvalidRequestError(
660
+ f"Association proxy received an unexpected error when "
661
+ f"trying to retreive attribute "
662
+ f'"{target_class.__name__}.{parent.value_attr}" from '
663
+ f'class "{target_class.__name__}": {err}'
664
+ ) from err
665
+ else:
666
+ return cls._construct_for_assoc(
667
+ target_assoc, parent, owning_class, target_class, value_attr
668
+ )
669
+
670
+ @classmethod
671
+ def _construct_for_assoc(
672
+ cls,
673
+ target_assoc: Optional[AssociationProxyInstance[_T]],
674
+ parent: _AssociationProxyProtocol[_T],
675
+ owning_class: Type[Any],
676
+ target_class: Type[Any],
677
+ value_attr: str,
678
+ ) -> AssociationProxyInstance[_T]:
679
+ if target_assoc is not None:
680
+ return ObjectAssociationProxyInstance(
681
+ parent, owning_class, target_class, value_attr
682
+ )
683
+
684
+ attr = getattr(target_class, value_attr)
685
+ if not hasattr(attr, "_is_internal_proxy"):
686
+ return AmbiguousAssociationProxyInstance(
687
+ parent, owning_class, target_class, value_attr
688
+ )
689
+ is_object = attr._impl_uses_objects
690
+ if is_object:
691
+ return ObjectAssociationProxyInstance(
692
+ parent, owning_class, target_class, value_attr
693
+ )
694
+ else:
695
+ return ColumnAssociationProxyInstance(
696
+ parent, owning_class, target_class, value_attr
697
+ )
698
+
699
+ def _get_property(self) -> MapperProperty[Any]:
700
+ return orm.class_mapper(self.owning_class).get_property(
701
+ self.target_collection
702
+ )
703
+
704
+ @property
705
+ def _comparator(self) -> PropComparator[Any]:
706
+ return getattr( # type: ignore
707
+ self.owning_class, self.target_collection
708
+ ).comparator
709
+
710
+ def __clause_element__(self) -> NoReturn:
711
+ raise NotImplementedError(
712
+ "The association proxy can't be used as a plain column "
713
+ "expression; it only works inside of a comparison expression"
714
+ )
715
+
716
+ @classmethod
717
+ def _cls_unwrap_target_assoc_proxy(
718
+ cls, target_class: Any, value_attr: str
719
+ ) -> Optional[AssociationProxyInstance[_T]]:
720
+ attr = getattr(target_class, value_attr)
721
+ assert not isinstance(attr, AssociationProxy)
722
+ if isinstance(attr, AssociationProxyInstance):
723
+ return attr
724
+ return None
725
+
726
+ @util.memoized_property
727
+ def _unwrap_target_assoc_proxy(
728
+ self,
729
+ ) -> Optional[AssociationProxyInstance[_T]]:
730
+ return self._cls_unwrap_target_assoc_proxy(
731
+ self.target_class, self.value_attr
732
+ )
733
+
734
+ @property
735
+ def remote_attr(self) -> SQLORMOperations[_T]:
736
+ """The 'remote' class attribute referenced by this
737
+ :class:`.AssociationProxyInstance`.
738
+
739
+ .. seealso::
740
+
741
+ :attr:`.AssociationProxyInstance.attr`
742
+
743
+ :attr:`.AssociationProxyInstance.local_attr`
744
+
745
+ """
746
+ return cast(
747
+ "SQLORMOperations[_T]", getattr(self.target_class, self.value_attr)
748
+ )
749
+
750
+ @property
751
+ def local_attr(self) -> SQLORMOperations[Any]:
752
+ """The 'local' class attribute referenced by this
753
+ :class:`.AssociationProxyInstance`.
754
+
755
+ .. seealso::
756
+
757
+ :attr:`.AssociationProxyInstance.attr`
758
+
759
+ :attr:`.AssociationProxyInstance.remote_attr`
760
+
761
+ """
762
+ return cast(
763
+ "SQLORMOperations[Any]",
764
+ getattr(self.owning_class, self.target_collection),
765
+ )
766
+
767
+ @property
768
+ def attr(self) -> Tuple[SQLORMOperations[Any], SQLORMOperations[_T]]:
769
+ """Return a tuple of ``(local_attr, remote_attr)``.
770
+
771
+ This attribute was originally intended to facilitate using the
772
+ :meth:`_query.Query.join` method to join across the two relationships
773
+ at once, however this makes use of a deprecated calling style.
774
+
775
+ To use :meth:`_sql.select.join` or :meth:`_orm.Query.join` with
776
+ an association proxy, the current method is to make use of the
777
+ :attr:`.AssociationProxyInstance.local_attr` and
778
+ :attr:`.AssociationProxyInstance.remote_attr` attributes separately::
779
+
780
+ stmt = (
781
+ select(Parent).
782
+ join(Parent.proxied.local_attr).
783
+ join(Parent.proxied.remote_attr)
784
+ )
785
+
786
+ A future release may seek to provide a more succinct join pattern
787
+ for association proxy attributes.
788
+
789
+ .. seealso::
790
+
791
+ :attr:`.AssociationProxyInstance.local_attr`
792
+
793
+ :attr:`.AssociationProxyInstance.remote_attr`
794
+
795
+ """
796
+ return (self.local_attr, self.remote_attr)
797
+
798
+ @util.memoized_property
799
+ def scalar(self) -> bool:
800
+ """Return ``True`` if this :class:`.AssociationProxyInstance`
801
+ proxies a scalar relationship on the local side."""
802
+
803
+ scalar = not self._get_property().uselist
804
+ if scalar:
805
+ self._initialize_scalar_accessors()
806
+ return scalar
807
+
808
+ @util.memoized_property
809
+ def _value_is_scalar(self) -> bool:
810
+ return (
811
+ not self._get_property()
812
+ .mapper.get_property(self.value_attr)
813
+ .uselist
814
+ )
815
+
816
+ @property
817
+ def _target_is_object(self) -> bool:
818
+ raise NotImplementedError()
819
+
820
+ _scalar_get: _GetterProtocol[_T]
821
+ _scalar_set: _PlainSetterProtocol[_T]
822
+
823
+ def _initialize_scalar_accessors(self) -> None:
824
+ if self.parent.getset_factory:
825
+ get, set_ = self.parent.getset_factory(None, self)
826
+ else:
827
+ get, set_ = self.parent._default_getset(None)
828
+ self._scalar_get, self._scalar_set = get, cast(
829
+ "_PlainSetterProtocol[_T]", set_
830
+ )
831
+
832
+ def _default_getset(
833
+ self, collection_class: Any
834
+ ) -> Tuple[_GetterProtocol[Any], _SetterProtocol]:
835
+ attr = self.value_attr
836
+ _getter = operator.attrgetter(attr)
837
+
838
+ def getter(instance: Any) -> Optional[_T]:
839
+ return _getter(instance) if instance is not None else None
840
+
841
+ if collection_class is dict:
842
+
843
+ def dict_setter(instance: Any, k: Any, value: _T) -> None:
844
+ setattr(instance, attr, value)
845
+
846
+ return getter, dict_setter
847
+ else:
848
+
849
+ def plain_setter(o: Any, v: _T) -> None:
850
+ setattr(o, attr, v)
851
+
852
+ return getter, plain_setter
853
+
854
+ @util.ro_non_memoized_property
855
+ def info(self) -> _InfoType:
856
+ return self.parent.info
857
+
858
+ @overload
859
+ def get(self: _Self, obj: Literal[None]) -> _Self: ...
860
+
861
+ @overload
862
+ def get(self, obj: Any) -> _T: ...
863
+
864
+ def get(
865
+ self, obj: Any
866
+ ) -> Union[Optional[_T], AssociationProxyInstance[_T]]:
867
+ if obj is None:
868
+ return self
869
+
870
+ proxy: _T
871
+
872
+ if self.scalar:
873
+ target = getattr(obj, self.target_collection)
874
+ return self._scalar_get(target)
875
+ else:
876
+ try:
877
+ # If the owning instance is reborn (orm session resurrect,
878
+ # etc.), refresh the proxy cache.
879
+ creator_id, self_id, proxy = cast(
880
+ "Tuple[int, int, _T]", getattr(obj, self.key)
881
+ )
882
+ except AttributeError:
883
+ pass
884
+ else:
885
+ if id(obj) == creator_id and id(self) == self_id:
886
+ assert self.collection_class is not None
887
+ return proxy
888
+
889
+ self.collection_class, proxy = self._new(
890
+ _lazy_collection(obj, self.target_collection)
891
+ )
892
+ setattr(obj, self.key, (id(obj), id(self), proxy))
893
+ return proxy
894
+
895
+ def set(self, obj: Any, values: _T) -> None:
896
+ if self.scalar:
897
+ creator = cast(
898
+ "_PlainCreatorProtocol[_T]",
899
+ (
900
+ self.parent.creator
901
+ if self.parent.creator
902
+ else self.target_class
903
+ ),
904
+ )
905
+ target = getattr(obj, self.target_collection)
906
+ if target is None:
907
+ if (
908
+ values is None
909
+ and not self.parent.create_on_none_assignment
910
+ ):
911
+ return
912
+ setattr(obj, self.target_collection, creator(values))
913
+ else:
914
+ self._scalar_set(target, values)
915
+ if values is None and self.parent.cascade_scalar_deletes:
916
+ setattr(obj, self.target_collection, None)
917
+ else:
918
+ proxy = self.get(obj)
919
+ assert self.collection_class is not None
920
+ if proxy is not values:
921
+ proxy._bulk_replace(self, values)
922
+
923
+ def delete(self, obj: Any) -> None:
924
+ if self.owning_class is None:
925
+ self._calc_owner(obj, None)
926
+
927
+ if self.scalar:
928
+ target = getattr(obj, self.target_collection)
929
+ if target is not None:
930
+ delattr(target, self.value_attr)
931
+ delattr(obj, self.target_collection)
932
+
933
+ def _new(
934
+ self, lazy_collection: _LazyCollectionProtocol[_T]
935
+ ) -> Tuple[Type[Any], _T]:
936
+ creator = (
937
+ self.parent.creator
938
+ if self.parent.creator is not None
939
+ else cast("_CreatorProtocol", self.target_class)
940
+ )
941
+ collection_class = util.duck_type_collection(lazy_collection())
942
+
943
+ if collection_class is None:
944
+ raise exc.InvalidRequestError(
945
+ f"lazy collection factory did not return a "
946
+ f"valid collection type, got {collection_class}"
947
+ )
948
+ if self.parent.proxy_factory:
949
+ return (
950
+ collection_class,
951
+ self.parent.proxy_factory(
952
+ lazy_collection, creator, self.value_attr, self
953
+ ),
954
+ )
955
+
956
+ if self.parent.getset_factory:
957
+ getter, setter = self.parent.getset_factory(collection_class, self)
958
+ else:
959
+ getter, setter = self.parent._default_getset(collection_class)
960
+
961
+ if collection_class is list:
962
+ return (
963
+ collection_class,
964
+ cast(
965
+ _T,
966
+ _AssociationList(
967
+ lazy_collection, creator, getter, setter, self
968
+ ),
969
+ ),
970
+ )
971
+ elif collection_class is dict:
972
+ return (
973
+ collection_class,
974
+ cast(
975
+ _T,
976
+ _AssociationDict(
977
+ lazy_collection, creator, getter, setter, self
978
+ ),
979
+ ),
980
+ )
981
+ elif collection_class is set:
982
+ return (
983
+ collection_class,
984
+ cast(
985
+ _T,
986
+ _AssociationSet(
987
+ lazy_collection, creator, getter, setter, self
988
+ ),
989
+ ),
990
+ )
991
+ else:
992
+ raise exc.ArgumentError(
993
+ "could not guess which interface to use for "
994
+ 'collection_class "%s" backing "%s"; specify a '
995
+ "proxy_factory and proxy_bulk_set manually"
996
+ % (self.collection_class, self.target_collection)
997
+ )
998
+
999
+ def _set(
1000
+ self, proxy: _AssociationCollection[Any], values: Iterable[Any]
1001
+ ) -> None:
1002
+ if self.parent.proxy_bulk_set:
1003
+ self.parent.proxy_bulk_set(proxy, values)
1004
+ elif self.collection_class is list:
1005
+ cast("_AssociationList[Any]", proxy).extend(values)
1006
+ elif self.collection_class is dict:
1007
+ cast("_AssociationDict[Any, Any]", proxy).update(values)
1008
+ elif self.collection_class is set:
1009
+ cast("_AssociationSet[Any]", proxy).update(values)
1010
+ else:
1011
+ raise exc.ArgumentError(
1012
+ "no proxy_bulk_set supplied for custom "
1013
+ "collection_class implementation"
1014
+ )
1015
+
1016
+ def _inflate(self, proxy: _AssociationCollection[Any]) -> None:
1017
+ creator = (
1018
+ self.parent.creator
1019
+ and self.parent.creator
1020
+ or cast(_CreatorProtocol, self.target_class)
1021
+ )
1022
+
1023
+ if self.parent.getset_factory:
1024
+ getter, setter = self.parent.getset_factory(
1025
+ self.collection_class, self
1026
+ )
1027
+ else:
1028
+ getter, setter = self.parent._default_getset(self.collection_class)
1029
+
1030
+ proxy.creator = creator
1031
+ proxy.getter = getter
1032
+ proxy.setter = setter
1033
+
1034
+ def _criterion_exists(
1035
+ self,
1036
+ criterion: Optional[_ColumnExpressionArgument[bool]] = None,
1037
+ **kwargs: Any,
1038
+ ) -> ColumnElement[bool]:
1039
+ is_has = kwargs.pop("is_has", None)
1040
+
1041
+ target_assoc = self._unwrap_target_assoc_proxy
1042
+ if target_assoc is not None:
1043
+ inner = target_assoc._criterion_exists(
1044
+ criterion=criterion, **kwargs
1045
+ )
1046
+ return self._comparator._criterion_exists(inner)
1047
+
1048
+ if self._target_is_object:
1049
+ attr = getattr(self.target_class, self.value_attr)
1050
+ value_expr = attr.comparator._criterion_exists(criterion, **kwargs)
1051
+ else:
1052
+ if kwargs:
1053
+ raise exc.ArgumentError(
1054
+ "Can't apply keyword arguments to column-targeted "
1055
+ "association proxy; use =="
1056
+ )
1057
+ elif is_has and criterion is not None:
1058
+ raise exc.ArgumentError(
1059
+ "Non-empty has() not allowed for "
1060
+ "column-targeted association proxy; use =="
1061
+ )
1062
+
1063
+ value_expr = criterion
1064
+
1065
+ return self._comparator._criterion_exists(value_expr)
1066
+
1067
+ def any(
1068
+ self,
1069
+ criterion: Optional[_ColumnExpressionArgument[bool]] = None,
1070
+ **kwargs: Any,
1071
+ ) -> ColumnElement[bool]:
1072
+ """Produce a proxied 'any' expression using EXISTS.
1073
+
1074
+ This expression will be a composed product
1075
+ using the :meth:`.Relationship.Comparator.any`
1076
+ and/or :meth:`.Relationship.Comparator.has`
1077
+ operators of the underlying proxied attributes.
1078
+
1079
+ """
1080
+ if self._unwrap_target_assoc_proxy is None and (
1081
+ self.scalar
1082
+ and (not self._target_is_object or self._value_is_scalar)
1083
+ ):
1084
+ raise exc.InvalidRequestError(
1085
+ "'any()' not implemented for scalar attributes. Use has()."
1086
+ )
1087
+ return self._criterion_exists(
1088
+ criterion=criterion, is_has=False, **kwargs
1089
+ )
1090
+
1091
+ def has(
1092
+ self,
1093
+ criterion: Optional[_ColumnExpressionArgument[bool]] = None,
1094
+ **kwargs: Any,
1095
+ ) -> ColumnElement[bool]:
1096
+ """Produce a proxied 'has' expression using EXISTS.
1097
+
1098
+ This expression will be a composed product
1099
+ using the :meth:`.Relationship.Comparator.any`
1100
+ and/or :meth:`.Relationship.Comparator.has`
1101
+ operators of the underlying proxied attributes.
1102
+
1103
+ """
1104
+ if self._unwrap_target_assoc_proxy is None and (
1105
+ not self.scalar
1106
+ or (self._target_is_object and not self._value_is_scalar)
1107
+ ):
1108
+ raise exc.InvalidRequestError(
1109
+ "'has()' not implemented for collections. Use any()."
1110
+ )
1111
+ return self._criterion_exists(
1112
+ criterion=criterion, is_has=True, **kwargs
1113
+ )
1114
+
1115
+ def __repr__(self) -> str:
1116
+ return "%s(%r)" % (self.__class__.__name__, self.parent)
1117
+
1118
+
1119
+ class AmbiguousAssociationProxyInstance(AssociationProxyInstance[_T]):
1120
+ """an :class:`.AssociationProxyInstance` where we cannot determine
1121
+ the type of target object.
1122
+ """
1123
+
1124
+ _is_canonical = False
1125
+
1126
+ def _ambiguous(self) -> NoReturn:
1127
+ raise AttributeError(
1128
+ "Association proxy %s.%s refers to an attribute '%s' that is not "
1129
+ "directly mapped on class %s; therefore this operation cannot "
1130
+ "proceed since we don't know what type of object is referred "
1131
+ "towards"
1132
+ % (
1133
+ self.owning_class.__name__,
1134
+ self.target_collection,
1135
+ self.value_attr,
1136
+ self.target_class,
1137
+ )
1138
+ )
1139
+
1140
+ def get(self, obj: Any) -> Any:
1141
+ if obj is None:
1142
+ return self
1143
+ else:
1144
+ return super().get(obj)
1145
+
1146
+ def __eq__(self, obj: object) -> NoReturn:
1147
+ self._ambiguous()
1148
+
1149
+ def __ne__(self, obj: object) -> NoReturn:
1150
+ self._ambiguous()
1151
+
1152
+ def any(
1153
+ self,
1154
+ criterion: Optional[_ColumnExpressionArgument[bool]] = None,
1155
+ **kwargs: Any,
1156
+ ) -> NoReturn:
1157
+ self._ambiguous()
1158
+
1159
+ def has(
1160
+ self,
1161
+ criterion: Optional[_ColumnExpressionArgument[bool]] = None,
1162
+ **kwargs: Any,
1163
+ ) -> NoReturn:
1164
+ self._ambiguous()
1165
+
1166
+ @util.memoized_property
1167
+ def _lookup_cache(self) -> Dict[Type[Any], AssociationProxyInstance[_T]]:
1168
+ # mapping of <subclass>->AssociationProxyInstance.
1169
+ # e.g. proxy is A-> A.b -> B -> B.b_attr, but B.b_attr doesn't exist;
1170
+ # only B1(B) and B2(B) have "b_attr", keys in here would be B1, B2
1171
+ return {}
1172
+
1173
+ def _non_canonical_get_for_object(
1174
+ self, parent_instance: Any
1175
+ ) -> AssociationProxyInstance[_T]:
1176
+ if parent_instance is not None:
1177
+ actual_obj = getattr(parent_instance, self.target_collection)
1178
+ if actual_obj is not None:
1179
+ try:
1180
+ insp = inspect(actual_obj)
1181
+ except exc.NoInspectionAvailable:
1182
+ pass
1183
+ else:
1184
+ mapper = insp.mapper
1185
+ instance_class = mapper.class_
1186
+ if instance_class not in self._lookup_cache:
1187
+ self._populate_cache(instance_class, mapper)
1188
+
1189
+ try:
1190
+ return self._lookup_cache[instance_class]
1191
+ except KeyError:
1192
+ pass
1193
+
1194
+ # no object or ambiguous object given, so return "self", which
1195
+ # is a proxy with generally only instance-level functionality
1196
+ return self
1197
+
1198
+ def _populate_cache(
1199
+ self, instance_class: Any, mapper: Mapper[Any]
1200
+ ) -> None:
1201
+ prop = orm.class_mapper(self.owning_class).get_property(
1202
+ self.target_collection
1203
+ )
1204
+
1205
+ if mapper.isa(prop.mapper):
1206
+ target_class = instance_class
1207
+ try:
1208
+ target_assoc = self._cls_unwrap_target_assoc_proxy(
1209
+ target_class, self.value_attr
1210
+ )
1211
+ except AttributeError:
1212
+ pass
1213
+ else:
1214
+ self._lookup_cache[instance_class] = self._construct_for_assoc(
1215
+ cast("AssociationProxyInstance[_T]", target_assoc),
1216
+ self.parent,
1217
+ self.owning_class,
1218
+ target_class,
1219
+ self.value_attr,
1220
+ )
1221
+
1222
+
1223
+ class ObjectAssociationProxyInstance(AssociationProxyInstance[_T]):
1224
+ """an :class:`.AssociationProxyInstance` that has an object as a target."""
1225
+
1226
+ _target_is_object: bool = True
1227
+ _is_canonical = True
1228
+
1229
+ def contains(self, other: Any, **kw: Any) -> ColumnElement[bool]:
1230
+ """Produce a proxied 'contains' expression using EXISTS.
1231
+
1232
+ This expression will be a composed product
1233
+ using the :meth:`.Relationship.Comparator.any`,
1234
+ :meth:`.Relationship.Comparator.has`,
1235
+ and/or :meth:`.Relationship.Comparator.contains`
1236
+ operators of the underlying proxied attributes.
1237
+ """
1238
+
1239
+ target_assoc = self._unwrap_target_assoc_proxy
1240
+ if target_assoc is not None:
1241
+ return self._comparator._criterion_exists(
1242
+ target_assoc.contains(other)
1243
+ if not target_assoc.scalar
1244
+ else target_assoc == other
1245
+ )
1246
+ elif (
1247
+ self._target_is_object
1248
+ and self.scalar
1249
+ and not self._value_is_scalar
1250
+ ):
1251
+ return self._comparator.has(
1252
+ getattr(self.target_class, self.value_attr).contains(other)
1253
+ )
1254
+ elif self._target_is_object and self.scalar and self._value_is_scalar:
1255
+ raise exc.InvalidRequestError(
1256
+ "contains() doesn't apply to a scalar object endpoint; use =="
1257
+ )
1258
+ else:
1259
+ return self._comparator._criterion_exists(
1260
+ **{self.value_attr: other}
1261
+ )
1262
+
1263
+ def __eq__(self, obj: Any) -> ColumnElement[bool]: # type: ignore[override] # noqa: E501
1264
+ # note the has() here will fail for collections; eq_()
1265
+ # is only allowed with a scalar.
1266
+ if obj is None:
1267
+ return or_(
1268
+ self._comparator.has(**{self.value_attr: obj}),
1269
+ self._comparator == None,
1270
+ )
1271
+ else:
1272
+ return self._comparator.has(**{self.value_attr: obj})
1273
+
1274
+ def __ne__(self, obj: Any) -> ColumnElement[bool]: # type: ignore[override] # noqa: E501
1275
+ # note the has() here will fail for collections; eq_()
1276
+ # is only allowed with a scalar.
1277
+ return self._comparator.has(
1278
+ getattr(self.target_class, self.value_attr) != obj
1279
+ )
1280
+
1281
+
1282
+ class ColumnAssociationProxyInstance(AssociationProxyInstance[_T]):
1283
+ """an :class:`.AssociationProxyInstance` that has a database column as a
1284
+ target.
1285
+ """
1286
+
1287
+ _target_is_object: bool = False
1288
+ _is_canonical = True
1289
+
1290
+ def __eq__(self, other: Any) -> ColumnElement[bool]: # type: ignore[override] # noqa: E501
1291
+ # special case "is None" to check for no related row as well
1292
+ expr = self._criterion_exists(
1293
+ self.remote_attr.operate(operators.eq, other)
1294
+ )
1295
+ if other is None:
1296
+ return or_(expr, self._comparator == None)
1297
+ else:
1298
+ return expr
1299
+
1300
+ def operate(
1301
+ self, op: operators.OperatorType, *other: Any, **kwargs: Any
1302
+ ) -> ColumnElement[Any]:
1303
+ return self._criterion_exists(
1304
+ self.remote_attr.operate(op, *other, **kwargs)
1305
+ )
1306
+
1307
+
1308
+ class _lazy_collection(_LazyCollectionProtocol[_T]):
1309
+ def __init__(self, obj: Any, target: str):
1310
+ self.parent = obj
1311
+ self.target = target
1312
+
1313
+ def __call__(
1314
+ self,
1315
+ ) -> Union[MutableSet[_T], MutableMapping[Any, _T], MutableSequence[_T]]:
1316
+ return getattr(self.parent, self.target) # type: ignore[no-any-return]
1317
+
1318
+ def __getstate__(self) -> Any:
1319
+ return {"obj": self.parent, "target": self.target}
1320
+
1321
+ def __setstate__(self, state: Any) -> None:
1322
+ self.parent = state["obj"]
1323
+ self.target = state["target"]
1324
+
1325
+
1326
+ _IT = TypeVar("_IT", bound="Any")
1327
+ """instance type - this is the type of object inside a collection.
1328
+
1329
+ this is not the same as the _T of AssociationProxy and
1330
+ AssociationProxyInstance itself, which will often refer to the
1331
+ collection[_IT] type.
1332
+
1333
+ """
1334
+
1335
+
1336
+ class _AssociationCollection(Generic[_IT]):
1337
+ getter: _GetterProtocol[_IT]
1338
+ """A function. Given an associated object, return the 'value'."""
1339
+
1340
+ creator: _CreatorProtocol
1341
+ """
1342
+ A function that creates new target entities. Given one parameter:
1343
+ value. This assertion is assumed::
1344
+
1345
+ obj = creator(somevalue)
1346
+ assert getter(obj) == somevalue
1347
+ """
1348
+
1349
+ parent: AssociationProxyInstance[_IT]
1350
+ setter: _SetterProtocol
1351
+ """A function. Given an associated object and a value, store that
1352
+ value on the object.
1353
+ """
1354
+
1355
+ lazy_collection: _LazyCollectionProtocol[_IT]
1356
+ """A callable returning a list-based collection of entities (usually an
1357
+ object attribute managed by a SQLAlchemy relationship())"""
1358
+
1359
+ def __init__(
1360
+ self,
1361
+ lazy_collection: _LazyCollectionProtocol[_IT],
1362
+ creator: _CreatorProtocol,
1363
+ getter: _GetterProtocol[_IT],
1364
+ setter: _SetterProtocol,
1365
+ parent: AssociationProxyInstance[_IT],
1366
+ ):
1367
+ """Constructs an _AssociationCollection.
1368
+
1369
+ This will always be a subclass of either _AssociationList,
1370
+ _AssociationSet, or _AssociationDict.
1371
+
1372
+ """
1373
+ self.lazy_collection = lazy_collection
1374
+ self.creator = creator
1375
+ self.getter = getter
1376
+ self.setter = setter
1377
+ self.parent = parent
1378
+
1379
+ if typing.TYPE_CHECKING:
1380
+ col: Collection[_IT]
1381
+ else:
1382
+ col = property(lambda self: self.lazy_collection())
1383
+
1384
+ def __len__(self) -> int:
1385
+ return len(self.col)
1386
+
1387
+ def __bool__(self) -> bool:
1388
+ return bool(self.col)
1389
+
1390
+ def __getstate__(self) -> Any:
1391
+ return {"parent": self.parent, "lazy_collection": self.lazy_collection}
1392
+
1393
+ def __setstate__(self, state: Any) -> None:
1394
+ self.parent = state["parent"]
1395
+ self.lazy_collection = state["lazy_collection"]
1396
+ self.parent._inflate(self)
1397
+
1398
+ def clear(self) -> None:
1399
+ raise NotImplementedError()
1400
+
1401
+
1402
+ class _AssociationSingleItem(_AssociationCollection[_T]):
1403
+ setter: _PlainSetterProtocol[_T]
1404
+ creator: _PlainCreatorProtocol[_T]
1405
+
1406
+ def _create(self, value: _T) -> Any:
1407
+ return self.creator(value)
1408
+
1409
+ def _get(self, object_: Any) -> _T:
1410
+ return self.getter(object_)
1411
+
1412
+ def _bulk_replace(
1413
+ self, assoc_proxy: AssociationProxyInstance[Any], values: Iterable[_IT]
1414
+ ) -> None:
1415
+ self.clear()
1416
+ assoc_proxy._set(self, values)
1417
+
1418
+
1419
+ class _AssociationList(_AssociationSingleItem[_T], MutableSequence[_T]):
1420
+ """Generic, converting, list-to-list proxy."""
1421
+
1422
+ col: MutableSequence[_T]
1423
+
1424
+ def _set(self, object_: Any, value: _T) -> None:
1425
+ self.setter(object_, value)
1426
+
1427
+ @overload
1428
+ def __getitem__(self, index: int) -> _T: ...
1429
+
1430
+ @overload
1431
+ def __getitem__(self, index: slice) -> MutableSequence[_T]: ...
1432
+
1433
+ def __getitem__(
1434
+ self, index: Union[int, slice]
1435
+ ) -> Union[_T, MutableSequence[_T]]:
1436
+ if not isinstance(index, slice):
1437
+ return self._get(self.col[index])
1438
+ else:
1439
+ return [self._get(member) for member in self.col[index]]
1440
+
1441
+ @overload
1442
+ def __setitem__(self, index: int, value: _T) -> None: ...
1443
+
1444
+ @overload
1445
+ def __setitem__(self, index: slice, value: Iterable[_T]) -> None: ...
1446
+
1447
+ def __setitem__(
1448
+ self, index: Union[int, slice], value: Union[_T, Iterable[_T]]
1449
+ ) -> None:
1450
+ if not isinstance(index, slice):
1451
+ self._set(self.col[index], cast("_T", value))
1452
+ else:
1453
+ if index.stop is None:
1454
+ stop = len(self)
1455
+ elif index.stop < 0:
1456
+ stop = len(self) + index.stop
1457
+ else:
1458
+ stop = index.stop
1459
+ step = index.step or 1
1460
+
1461
+ start = index.start or 0
1462
+ rng = list(range(index.start or 0, stop, step))
1463
+
1464
+ sized_value = list(value)
1465
+
1466
+ if step == 1:
1467
+ for i in rng:
1468
+ del self[start]
1469
+ i = start
1470
+ for item in sized_value:
1471
+ self.insert(i, item)
1472
+ i += 1
1473
+ else:
1474
+ if len(sized_value) != len(rng):
1475
+ raise ValueError(
1476
+ "attempt to assign sequence of size %s to "
1477
+ "extended slice of size %s"
1478
+ % (len(sized_value), len(rng))
1479
+ )
1480
+ for i, item in zip(rng, value):
1481
+ self._set(self.col[i], item)
1482
+
1483
+ @overload
1484
+ def __delitem__(self, index: int) -> None: ...
1485
+
1486
+ @overload
1487
+ def __delitem__(self, index: slice) -> None: ...
1488
+
1489
+ def __delitem__(self, index: Union[slice, int]) -> None:
1490
+ del self.col[index]
1491
+
1492
+ def __contains__(self, value: object) -> bool:
1493
+ for member in self.col:
1494
+ # testlib.pragma exempt:__eq__
1495
+ if self._get(member) == value:
1496
+ return True
1497
+ return False
1498
+
1499
+ def __iter__(self) -> Iterator[_T]:
1500
+ """Iterate over proxied values.
1501
+
1502
+ For the actual domain objects, iterate over .col instead or
1503
+ just use the underlying collection directly from its property
1504
+ on the parent.
1505
+ """
1506
+
1507
+ for member in self.col:
1508
+ yield self._get(member)
1509
+ return
1510
+
1511
+ def append(self, value: _T) -> None:
1512
+ col = self.col
1513
+ item = self._create(value)
1514
+ col.append(item)
1515
+
1516
+ def count(self, value: Any) -> int:
1517
+ count = 0
1518
+ for v in self:
1519
+ if v == value:
1520
+ count += 1
1521
+ return count
1522
+
1523
+ def extend(self, values: Iterable[_T]) -> None:
1524
+ for v in values:
1525
+ self.append(v)
1526
+
1527
+ def insert(self, index: int, value: _T) -> None:
1528
+ self.col[index:index] = [self._create(value)]
1529
+
1530
+ def pop(self, index: int = -1) -> _T:
1531
+ return self.getter(self.col.pop(index))
1532
+
1533
+ def remove(self, value: _T) -> None:
1534
+ for i, val in enumerate(self):
1535
+ if val == value:
1536
+ del self.col[i]
1537
+ return
1538
+ raise ValueError("value not in list")
1539
+
1540
+ def reverse(self) -> NoReturn:
1541
+ """Not supported, use reversed(mylist)"""
1542
+
1543
+ raise NotImplementedError()
1544
+
1545
+ def sort(self) -> NoReturn:
1546
+ """Not supported, use sorted(mylist)"""
1547
+
1548
+ raise NotImplementedError()
1549
+
1550
+ def clear(self) -> None:
1551
+ del self.col[0 : len(self.col)]
1552
+
1553
+ def __eq__(self, other: object) -> bool:
1554
+ return list(self) == other
1555
+
1556
+ def __ne__(self, other: object) -> bool:
1557
+ return list(self) != other
1558
+
1559
+ def __lt__(self, other: List[_T]) -> bool:
1560
+ return list(self) < other
1561
+
1562
+ def __le__(self, other: List[_T]) -> bool:
1563
+ return list(self) <= other
1564
+
1565
+ def __gt__(self, other: List[_T]) -> bool:
1566
+ return list(self) > other
1567
+
1568
+ def __ge__(self, other: List[_T]) -> bool:
1569
+ return list(self) >= other
1570
+
1571
+ def __add__(self, other: List[_T]) -> List[_T]:
1572
+ try:
1573
+ other = list(other)
1574
+ except TypeError:
1575
+ return NotImplemented
1576
+ return list(self) + other
1577
+
1578
+ def __radd__(self, other: List[_T]) -> List[_T]:
1579
+ try:
1580
+ other = list(other)
1581
+ except TypeError:
1582
+ return NotImplemented
1583
+ return other + list(self)
1584
+
1585
+ def __mul__(self, n: SupportsIndex) -> List[_T]:
1586
+ if not isinstance(n, int):
1587
+ return NotImplemented
1588
+ return list(self) * n
1589
+
1590
+ def __rmul__(self, n: SupportsIndex) -> List[_T]:
1591
+ if not isinstance(n, int):
1592
+ return NotImplemented
1593
+ return n * list(self)
1594
+
1595
+ def __iadd__(self, iterable: Iterable[_T]) -> Self:
1596
+ self.extend(iterable)
1597
+ return self
1598
+
1599
+ def __imul__(self, n: SupportsIndex) -> Self:
1600
+ # unlike a regular list *=, proxied __imul__ will generate unique
1601
+ # backing objects for each copy. *= on proxied lists is a bit of
1602
+ # a stretch anyhow, and this interpretation of the __imul__ contract
1603
+ # is more plausibly useful than copying the backing objects.
1604
+ if not isinstance(n, int):
1605
+ raise NotImplementedError()
1606
+ if n == 0:
1607
+ self.clear()
1608
+ elif n > 1:
1609
+ self.extend(list(self) * (n - 1))
1610
+ return self
1611
+
1612
+ if typing.TYPE_CHECKING:
1613
+ # TODO: no idea how to do this without separate "stub"
1614
+ def index(
1615
+ self, value: Any, start: int = ..., stop: int = ...
1616
+ ) -> int: ...
1617
+
1618
+ else:
1619
+
1620
+ def index(self, value: Any, *arg) -> int:
1621
+ ls = list(self)
1622
+ return ls.index(value, *arg)
1623
+
1624
+ def copy(self) -> List[_T]:
1625
+ return list(self)
1626
+
1627
+ def __repr__(self) -> str:
1628
+ return repr(list(self))
1629
+
1630
+ def __hash__(self) -> NoReturn:
1631
+ raise TypeError("%s objects are unhashable" % type(self).__name__)
1632
+
1633
+ if not typing.TYPE_CHECKING:
1634
+ for func_name, func in list(locals().items()):
1635
+ if (
1636
+ callable(func)
1637
+ and func.__name__ == func_name
1638
+ and not func.__doc__
1639
+ and hasattr(list, func_name)
1640
+ ):
1641
+ func.__doc__ = getattr(list, func_name).__doc__
1642
+ del func_name, func
1643
+
1644
+
1645
+ class _AssociationDict(_AssociationCollection[_VT], MutableMapping[_KT, _VT]):
1646
+ """Generic, converting, dict-to-dict proxy."""
1647
+
1648
+ setter: _DictSetterProtocol[_VT]
1649
+ creator: _KeyCreatorProtocol[_VT]
1650
+ col: MutableMapping[_KT, Optional[_VT]]
1651
+
1652
+ def _create(self, key: _KT, value: Optional[_VT]) -> Any:
1653
+ return self.creator(key, value)
1654
+
1655
+ def _get(self, object_: Any) -> _VT:
1656
+ return self.getter(object_)
1657
+
1658
+ def _set(self, object_: Any, key: _KT, value: _VT) -> None:
1659
+ return self.setter(object_, key, value)
1660
+
1661
+ def __getitem__(self, key: _KT) -> _VT:
1662
+ return self._get(self.col[key])
1663
+
1664
+ def __setitem__(self, key: _KT, value: _VT) -> None:
1665
+ if key in self.col:
1666
+ self._set(self.col[key], key, value)
1667
+ else:
1668
+ self.col[key] = self._create(key, value)
1669
+
1670
+ def __delitem__(self, key: _KT) -> None:
1671
+ del self.col[key]
1672
+
1673
+ def __contains__(self, key: object) -> bool:
1674
+ return key in self.col
1675
+
1676
+ def __iter__(self) -> Iterator[_KT]:
1677
+ return iter(self.col.keys())
1678
+
1679
+ def clear(self) -> None:
1680
+ self.col.clear()
1681
+
1682
+ def __eq__(self, other: object) -> bool:
1683
+ return dict(self) == other
1684
+
1685
+ def __ne__(self, other: object) -> bool:
1686
+ return dict(self) != other
1687
+
1688
+ def __repr__(self) -> str:
1689
+ return repr(dict(self))
1690
+
1691
+ @overload
1692
+ def get(self, __key: _KT) -> Optional[_VT]: ...
1693
+
1694
+ @overload
1695
+ def get(self, __key: _KT, default: Union[_VT, _T]) -> Union[_VT, _T]: ...
1696
+
1697
+ def get(
1698
+ self, key: _KT, default: Optional[Union[_VT, _T]] = None
1699
+ ) -> Union[_VT, _T, None]:
1700
+ try:
1701
+ return self[key]
1702
+ except KeyError:
1703
+ return default
1704
+
1705
+ def setdefault(self, key: _KT, default: Optional[_VT] = None) -> _VT:
1706
+ # TODO: again, no idea how to create an actual MutableMapping.
1707
+ # default must allow None, return type can't include None,
1708
+ # the stub explicitly allows for default of None with a cryptic message
1709
+ # "This overload should be allowed only if the value type is
1710
+ # compatible with None.".
1711
+ if key not in self.col:
1712
+ self.col[key] = self._create(key, default)
1713
+ return default # type: ignore
1714
+ else:
1715
+ return self[key]
1716
+
1717
+ def keys(self) -> KeysView[_KT]:
1718
+ return self.col.keys()
1719
+
1720
+ def items(self) -> ItemsView[_KT, _VT]:
1721
+ return ItemsView(self)
1722
+
1723
+ def values(self) -> ValuesView[_VT]:
1724
+ return ValuesView(self)
1725
+
1726
+ @overload
1727
+ def pop(self, __key: _KT) -> _VT: ...
1728
+
1729
+ @overload
1730
+ def pop(
1731
+ self, __key: _KT, default: Union[_VT, _T] = ...
1732
+ ) -> Union[_VT, _T]: ...
1733
+
1734
+ def pop(self, __key: _KT, *arg: Any, **kw: Any) -> Union[_VT, _T]:
1735
+ member = self.col.pop(__key, *arg, **kw)
1736
+ return self._get(member)
1737
+
1738
+ def popitem(self) -> Tuple[_KT, _VT]:
1739
+ item = self.col.popitem()
1740
+ return (item[0], self._get(item[1]))
1741
+
1742
+ @overload
1743
+ def update(
1744
+ self, __m: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT
1745
+ ) -> None: ...
1746
+
1747
+ @overload
1748
+ def update(
1749
+ self, __m: Iterable[tuple[_KT, _VT]], **kwargs: _VT
1750
+ ) -> None: ...
1751
+
1752
+ @overload
1753
+ def update(self, **kwargs: _VT) -> None: ...
1754
+
1755
+ def update(self, *a: Any, **kw: Any) -> None:
1756
+ up: Dict[_KT, _VT] = {}
1757
+ up.update(*a, **kw)
1758
+
1759
+ for key, value in up.items():
1760
+ self[key] = value
1761
+
1762
+ def _bulk_replace(
1763
+ self,
1764
+ assoc_proxy: AssociationProxyInstance[Any],
1765
+ values: Mapping[_KT, _VT],
1766
+ ) -> None:
1767
+ existing = set(self)
1768
+ constants = existing.intersection(values or ())
1769
+ additions = set(values or ()).difference(constants)
1770
+ removals = existing.difference(constants)
1771
+
1772
+ for key, member in values.items() or ():
1773
+ if key in additions:
1774
+ self[key] = member
1775
+ elif key in constants:
1776
+ self[key] = member
1777
+
1778
+ for key in removals:
1779
+ del self[key]
1780
+
1781
+ def copy(self) -> Dict[_KT, _VT]:
1782
+ return dict(self.items())
1783
+
1784
+ def __hash__(self) -> NoReturn:
1785
+ raise TypeError("%s objects are unhashable" % type(self).__name__)
1786
+
1787
+ if not typing.TYPE_CHECKING:
1788
+ for func_name, func in list(locals().items()):
1789
+ if (
1790
+ callable(func)
1791
+ and func.__name__ == func_name
1792
+ and not func.__doc__
1793
+ and hasattr(dict, func_name)
1794
+ ):
1795
+ func.__doc__ = getattr(dict, func_name).__doc__
1796
+ del func_name, func
1797
+
1798
+
1799
+ class _AssociationSet(_AssociationSingleItem[_T], MutableSet[_T]):
1800
+ """Generic, converting, set-to-set proxy."""
1801
+
1802
+ col: MutableSet[_T]
1803
+
1804
+ def __len__(self) -> int:
1805
+ return len(self.col)
1806
+
1807
+ def __bool__(self) -> bool:
1808
+ if self.col:
1809
+ return True
1810
+ else:
1811
+ return False
1812
+
1813
+ def __contains__(self, __o: object) -> bool:
1814
+ for member in self.col:
1815
+ if self._get(member) == __o:
1816
+ return True
1817
+ return False
1818
+
1819
+ def __iter__(self) -> Iterator[_T]:
1820
+ """Iterate over proxied values.
1821
+
1822
+ For the actual domain objects, iterate over .col instead or just use
1823
+ the underlying collection directly from its property on the parent.
1824
+
1825
+ """
1826
+ for member in self.col:
1827
+ yield self._get(member)
1828
+ return
1829
+
1830
+ def add(self, __element: _T) -> None:
1831
+ if __element not in self:
1832
+ self.col.add(self._create(__element))
1833
+
1834
+ # for discard and remove, choosing a more expensive check strategy rather
1835
+ # than call self.creator()
1836
+ def discard(self, __element: _T) -> None:
1837
+ for member in self.col:
1838
+ if self._get(member) == __element:
1839
+ self.col.discard(member)
1840
+ break
1841
+
1842
+ def remove(self, __element: _T) -> None:
1843
+ for member in self.col:
1844
+ if self._get(member) == __element:
1845
+ self.col.discard(member)
1846
+ return
1847
+ raise KeyError(__element)
1848
+
1849
+ def pop(self) -> _T:
1850
+ if not self.col:
1851
+ raise KeyError("pop from an empty set")
1852
+ member = self.col.pop()
1853
+ return self._get(member)
1854
+
1855
+ def update(self, *s: Iterable[_T]) -> None:
1856
+ for iterable in s:
1857
+ for value in iterable:
1858
+ self.add(value)
1859
+
1860
+ def _bulk_replace(self, assoc_proxy: Any, values: Iterable[_T]) -> None:
1861
+ existing = set(self)
1862
+ constants = existing.intersection(values or ())
1863
+ additions = set(values or ()).difference(constants)
1864
+ removals = existing.difference(constants)
1865
+
1866
+ appender = self.add
1867
+ remover = self.remove
1868
+
1869
+ for member in values or ():
1870
+ if member in additions:
1871
+ appender(member)
1872
+ elif member in constants:
1873
+ appender(member)
1874
+
1875
+ for member in removals:
1876
+ remover(member)
1877
+
1878
+ def __ior__( # type: ignore
1879
+ self, other: AbstractSet[_S]
1880
+ ) -> MutableSet[Union[_T, _S]]:
1881
+ if not collections._set_binops_check_strict(self, other):
1882
+ raise NotImplementedError()
1883
+ for value in other:
1884
+ self.add(value)
1885
+ return self
1886
+
1887
+ def _set(self) -> Set[_T]:
1888
+ return set(iter(self))
1889
+
1890
+ def union(self, *s: Iterable[_S]) -> MutableSet[Union[_T, _S]]:
1891
+ return set(self).union(*s)
1892
+
1893
+ def __or__(self, __s: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]:
1894
+ return self.union(__s)
1895
+
1896
+ def difference(self, *s: Iterable[Any]) -> MutableSet[_T]:
1897
+ return set(self).difference(*s)
1898
+
1899
+ def __sub__(self, s: AbstractSet[Any]) -> MutableSet[_T]:
1900
+ return self.difference(s)
1901
+
1902
+ def difference_update(self, *s: Iterable[Any]) -> None:
1903
+ for other in s:
1904
+ for value in other:
1905
+ self.discard(value)
1906
+
1907
+ def __isub__(self, s: AbstractSet[Any]) -> Self:
1908
+ if not collections._set_binops_check_strict(self, s):
1909
+ raise NotImplementedError()
1910
+ for value in s:
1911
+ self.discard(value)
1912
+ return self
1913
+
1914
+ def intersection(self, *s: Iterable[Any]) -> MutableSet[_T]:
1915
+ return set(self).intersection(*s)
1916
+
1917
+ def __and__(self, s: AbstractSet[Any]) -> MutableSet[_T]:
1918
+ return self.intersection(s)
1919
+
1920
+ def intersection_update(self, *s: Iterable[Any]) -> None:
1921
+ for other in s:
1922
+ want, have = self.intersection(other), set(self)
1923
+
1924
+ remove, add = have - want, want - have
1925
+
1926
+ for value in remove:
1927
+ self.remove(value)
1928
+ for value in add:
1929
+ self.add(value)
1930
+
1931
+ def __iand__(self, s: AbstractSet[Any]) -> Self:
1932
+ if not collections._set_binops_check_strict(self, s):
1933
+ raise NotImplementedError()
1934
+ want = self.intersection(s)
1935
+ have: Set[_T] = set(self)
1936
+
1937
+ remove, add = have - want, want - have
1938
+
1939
+ for value in remove:
1940
+ self.remove(value)
1941
+ for value in add:
1942
+ self.add(value)
1943
+ return self
1944
+
1945
+ def symmetric_difference(self, __s: Iterable[_T]) -> MutableSet[_T]:
1946
+ return set(self).symmetric_difference(__s)
1947
+
1948
+ def __xor__(self, s: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]:
1949
+ return self.symmetric_difference(s)
1950
+
1951
+ def symmetric_difference_update(self, other: Iterable[Any]) -> None:
1952
+ want, have = self.symmetric_difference(other), set(self)
1953
+
1954
+ remove, add = have - want, want - have
1955
+
1956
+ for value in remove:
1957
+ self.remove(value)
1958
+ for value in add:
1959
+ self.add(value)
1960
+
1961
+ def __ixor__(self, other: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: # type: ignore # noqa: E501
1962
+ if not collections._set_binops_check_strict(self, other):
1963
+ raise NotImplementedError()
1964
+
1965
+ self.symmetric_difference_update(other)
1966
+ return self
1967
+
1968
+ def issubset(self, __s: Iterable[Any]) -> bool:
1969
+ return set(self).issubset(__s)
1970
+
1971
+ def issuperset(self, __s: Iterable[Any]) -> bool:
1972
+ return set(self).issuperset(__s)
1973
+
1974
+ def clear(self) -> None:
1975
+ self.col.clear()
1976
+
1977
+ def copy(self) -> AbstractSet[_T]:
1978
+ return set(self)
1979
+
1980
+ def __eq__(self, other: object) -> bool:
1981
+ return set(self) == other
1982
+
1983
+ def __ne__(self, other: object) -> bool:
1984
+ return set(self) != other
1985
+
1986
+ def __lt__(self, other: AbstractSet[Any]) -> bool:
1987
+ return set(self) < other
1988
+
1989
+ def __le__(self, other: AbstractSet[Any]) -> bool:
1990
+ return set(self) <= other
1991
+
1992
+ def __gt__(self, other: AbstractSet[Any]) -> bool:
1993
+ return set(self) > other
1994
+
1995
+ def __ge__(self, other: AbstractSet[Any]) -> bool:
1996
+ return set(self) >= other
1997
+
1998
+ def __repr__(self) -> str:
1999
+ return repr(set(self))
2000
+
2001
+ def __hash__(self) -> NoReturn:
2002
+ raise TypeError("%s objects are unhashable" % type(self).__name__)
2003
+
2004
+ if not typing.TYPE_CHECKING:
2005
+ for func_name, func in list(locals().items()):
2006
+ if (
2007
+ callable(func)
2008
+ and func.__name__ == func_name
2009
+ and not func.__doc__
2010
+ and hasattr(set, func_name)
2011
+ ):
2012
+ func.__doc__ = getattr(set, func_name).__doc__
2013
+ del func_name, func