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