collections.py 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627
  1. # orm/collections.py
  2. # Copyright (C) 2005-2025 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. # mypy: allow-untyped-defs, allow-untyped-calls
  8. """Support for collections of mapped entities.
  9. The collections package supplies the machinery used to inform the ORM of
  10. collection membership changes. An instrumentation via decoration approach is
  11. used, allowing arbitrary types (including built-ins) to be used as entity
  12. collections without requiring inheritance from a base class.
  13. Instrumentation decoration relays membership change events to the
  14. :class:`.CollectionAttributeImpl` that is currently managing the collection.
  15. The decorators observe function call arguments and return values, tracking
  16. entities entering or leaving the collection. Two decorator approaches are
  17. provided. One is a bundle of generic decorators that map function arguments
  18. and return values to events::
  19. from sqlalchemy.orm.collections import collection
  20. class MyClass:
  21. # ...
  22. @collection.adds(1)
  23. def store(self, item):
  24. self.data.append(item)
  25. @collection.removes_return()
  26. def pop(self):
  27. return self.data.pop()
  28. The second approach is a bundle of targeted decorators that wrap appropriate
  29. append and remove notifiers around the mutation methods present in the
  30. standard Python ``list``, ``set`` and ``dict`` interfaces. These could be
  31. specified in terms of generic decorator recipes, but are instead hand-tooled
  32. for increased efficiency. The targeted decorators occasionally implement
  33. adapter-like behavior, such as mapping bulk-set methods (``extend``,
  34. ``update``, ``__setslice__``, etc.) into the series of atomic mutation events
  35. that the ORM requires.
  36. The targeted decorators are used internally for automatic instrumentation of
  37. entity collection classes. Every collection class goes through a
  38. transformation process roughly like so:
  39. 1. If the class is a built-in, substitute a trivial sub-class
  40. 2. Is this class already instrumented?
  41. 3. Add in generic decorators
  42. 4. Sniff out the collection interface through duck-typing
  43. 5. Add targeted decoration to any undecorated interface method
  44. This process modifies the class at runtime, decorating methods and adding some
  45. bookkeeping properties. This isn't possible (or desirable) for built-in
  46. classes like ``list``, so trivial sub-classes are substituted to hold
  47. decoration::
  48. class InstrumentedList(list):
  49. pass
  50. Collection classes can be specified in ``relationship(collection_class=)`` as
  51. types or a function that returns an instance. Collection classes are
  52. inspected and instrumented during the mapper compilation phase. The
  53. collection_class callable will be executed once to produce a specimen
  54. instance, and the type of that specimen will be instrumented. Functions that
  55. return built-in types like ``lists`` will be adapted to produce instrumented
  56. instances.
  57. When extending a known type like ``list``, additional decorations are not
  58. generally not needed. Odds are, the extension method will delegate to a
  59. method that's already instrumented. For example::
  60. class QueueIsh(list):
  61. def push(self, item):
  62. self.append(item)
  63. def shift(self):
  64. return self.pop(0)
  65. There's no need to decorate these methods. ``append`` and ``pop`` are already
  66. instrumented as part of the ``list`` interface. Decorating them would fire
  67. duplicate events, which should be avoided.
  68. The targeted decoration tries not to rely on other methods in the underlying
  69. collection class, but some are unavoidable. Many depend on 'read' methods
  70. being present to properly instrument a 'write', for example, ``__setitem__``
  71. needs ``__getitem__``. "Bulk" methods like ``update`` and ``extend`` may also
  72. reimplemented in terms of atomic appends and removes, so the ``extend``
  73. decoration will actually perform many ``append`` operations and not call the
  74. underlying method at all.
  75. Tight control over bulk operation and the firing of events is also possible by
  76. implementing the instrumentation internally in your methods. The basic
  77. instrumentation package works under the general assumption that collection
  78. mutation will not raise unusual exceptions. If you want to closely
  79. orchestrate append and remove events with exception management, internal
  80. instrumentation may be the answer. Within your method,
  81. ``collection_adapter(self)`` will retrieve an object that you can use for
  82. explicit control over triggering append and remove events.
  83. The owning object and :class:`.CollectionAttributeImpl` are also reachable
  84. through the adapter, allowing for some very sophisticated behavior.
  85. """
  86. from __future__ import annotations
  87. import operator
  88. import threading
  89. import typing
  90. from typing import Any
  91. from typing import Callable
  92. from typing import cast
  93. from typing import Collection
  94. from typing import Dict
  95. from typing import Iterable
  96. from typing import List
  97. from typing import NoReturn
  98. from typing import Optional
  99. from typing import Set
  100. from typing import Tuple
  101. from typing import Type
  102. from typing import TYPE_CHECKING
  103. from typing import TypeVar
  104. from typing import Union
  105. import weakref
  106. from .base import NO_KEY
  107. from .. import exc as sa_exc
  108. from .. import util
  109. from ..sql.base import NO_ARG
  110. from ..util.compat import inspect_getfullargspec
  111. from ..util.typing import Protocol
  112. if typing.TYPE_CHECKING:
  113. from .attributes import AttributeEventToken
  114. from .attributes import CollectionAttributeImpl
  115. from .mapped_collection import attribute_keyed_dict
  116. from .mapped_collection import column_keyed_dict
  117. from .mapped_collection import keyfunc_mapping
  118. from .mapped_collection import KeyFuncDict # noqa: F401
  119. from .state import InstanceState
  120. __all__ = [
  121. "collection",
  122. "collection_adapter",
  123. "keyfunc_mapping",
  124. "column_keyed_dict",
  125. "attribute_keyed_dict",
  126. "KeyFuncDict",
  127. # old names in < 2.0
  128. "mapped_collection",
  129. "column_mapped_collection",
  130. "attribute_mapped_collection",
  131. "MappedCollection",
  132. ]
  133. __instrumentation_mutex = threading.Lock()
  134. _CollectionFactoryType = Callable[[], "_AdaptedCollectionProtocol"]
  135. _T = TypeVar("_T", bound=Any)
  136. _KT = TypeVar("_KT", bound=Any)
  137. _VT = TypeVar("_VT", bound=Any)
  138. _COL = TypeVar("_COL", bound="Collection[Any]")
  139. _FN = TypeVar("_FN", bound="Callable[..., Any]")
  140. class _CollectionConverterProtocol(Protocol):
  141. def __call__(self, collection: _COL) -> _COL: ...
  142. class _AdaptedCollectionProtocol(Protocol):
  143. _sa_adapter: CollectionAdapter
  144. _sa_appender: Callable[..., Any]
  145. _sa_remover: Callable[..., Any]
  146. _sa_iterator: Callable[..., Iterable[Any]]
  147. _sa_converter: _CollectionConverterProtocol
  148. class collection:
  149. """Decorators for entity collection classes.
  150. The decorators fall into two groups: annotations and interception recipes.
  151. The annotating decorators (appender, remover, iterator, converter,
  152. internally_instrumented) indicate the method's purpose and take no
  153. arguments. They are not written with parens::
  154. @collection.appender
  155. def append(self, append): ...
  156. The recipe decorators all require parens, even those that take no
  157. arguments::
  158. @collection.adds("entity")
  159. def insert(self, position, entity): ...
  160. @collection.removes_return()
  161. def popitem(self): ...
  162. """
  163. # Bundled as a class solely for ease of use: packaging, doc strings,
  164. # importability.
  165. @staticmethod
  166. def appender(fn):
  167. """Tag the method as the collection appender.
  168. The appender method is called with one positional argument: the value
  169. to append. The method will be automatically decorated with 'adds(1)'
  170. if not already decorated::
  171. @collection.appender
  172. def add(self, append): ...
  173. # or, equivalently
  174. @collection.appender
  175. @collection.adds(1)
  176. def add(self, append): ...
  177. # for mapping type, an 'append' may kick out a previous value
  178. # that occupies that slot. consider d['a'] = 'foo'- any previous
  179. # value in d['a'] is discarded.
  180. @collection.appender
  181. @collection.replaces(1)
  182. def add(self, entity):
  183. key = some_key_func(entity)
  184. previous = None
  185. if key in self:
  186. previous = self[key]
  187. self[key] = entity
  188. return previous
  189. If the value to append is not allowed in the collection, you may
  190. raise an exception. Something to remember is that the appender
  191. will be called for each object mapped by a database query. If the
  192. database contains rows that violate your collection semantics, you
  193. will need to get creative to fix the problem, as access via the
  194. collection will not work.
  195. If the appender method is internally instrumented, you must also
  196. receive the keyword argument '_sa_initiator' and ensure its
  197. promulgation to collection events.
  198. """
  199. fn._sa_instrument_role = "appender"
  200. return fn
  201. @staticmethod
  202. def remover(fn):
  203. """Tag the method as the collection remover.
  204. The remover method is called with one positional argument: the value
  205. to remove. The method will be automatically decorated with
  206. :meth:`removes_return` if not already decorated::
  207. @collection.remover
  208. def zap(self, entity): ...
  209. # or, equivalently
  210. @collection.remover
  211. @collection.removes_return()
  212. def zap(self): ...
  213. If the value to remove is not present in the collection, you may
  214. raise an exception or return None to ignore the error.
  215. If the remove method is internally instrumented, you must also
  216. receive the keyword argument '_sa_initiator' and ensure its
  217. promulgation to collection events.
  218. """
  219. fn._sa_instrument_role = "remover"
  220. return fn
  221. @staticmethod
  222. def iterator(fn):
  223. """Tag the method as the collection remover.
  224. The iterator method is called with no arguments. It is expected to
  225. return an iterator over all collection members::
  226. @collection.iterator
  227. def __iter__(self): ...
  228. """
  229. fn._sa_instrument_role = "iterator"
  230. return fn
  231. @staticmethod
  232. def internally_instrumented(fn):
  233. """Tag the method as instrumented.
  234. This tag will prevent any decoration from being applied to the
  235. method. Use this if you are orchestrating your own calls to
  236. :func:`.collection_adapter` in one of the basic SQLAlchemy
  237. interface methods, or to prevent an automatic ABC method
  238. decoration from wrapping your implementation::
  239. # normally an 'extend' method on a list-like class would be
  240. # automatically intercepted and re-implemented in terms of
  241. # SQLAlchemy events and append(). your implementation will
  242. # never be called, unless:
  243. @collection.internally_instrumented
  244. def extend(self, items): ...
  245. """
  246. fn._sa_instrumented = True
  247. return fn
  248. @staticmethod
  249. @util.deprecated(
  250. "1.3",
  251. "The :meth:`.collection.converter` handler is deprecated and will "
  252. "be removed in a future release. Please refer to the "
  253. ":class:`.AttributeEvents.bulk_replace` listener interface in "
  254. "conjunction with the :func:`.event.listen` function.",
  255. )
  256. def converter(fn):
  257. """Tag the method as the collection converter.
  258. This optional method will be called when a collection is being
  259. replaced entirely, as in::
  260. myobj.acollection = [newvalue1, newvalue2]
  261. The converter method will receive the object being assigned and should
  262. return an iterable of values suitable for use by the ``appender``
  263. method. A converter must not assign values or mutate the collection,
  264. its sole job is to adapt the value the user provides into an iterable
  265. of values for the ORM's use.
  266. The default converter implementation will use duck-typing to do the
  267. conversion. A dict-like collection will be convert into an iterable
  268. of dictionary values, and other types will simply be iterated::
  269. @collection.converter
  270. def convert(self, other): ...
  271. If the duck-typing of the object does not match the type of this
  272. collection, a TypeError is raised.
  273. Supply an implementation of this method if you want to expand the
  274. range of possible types that can be assigned in bulk or perform
  275. validation on the values about to be assigned.
  276. """
  277. fn._sa_instrument_role = "converter"
  278. return fn
  279. @staticmethod
  280. def adds(arg: int) -> Callable[[_FN], _FN]:
  281. """Mark the method as adding an entity to the collection.
  282. Adds "add to collection" handling to the method. The decorator
  283. argument indicates which method argument holds the SQLAlchemy-relevant
  284. value. Arguments can be specified positionally (i.e. integer) or by
  285. name::
  286. @collection.adds(1)
  287. def push(self, item): ...
  288. @collection.adds("entity")
  289. def do_stuff(self, thing, entity=None): ...
  290. """
  291. def decorator(fn):
  292. fn._sa_instrument_before = ("fire_append_event", arg)
  293. return fn
  294. return decorator
  295. @staticmethod
  296. def replaces(arg):
  297. """Mark the method as replacing an entity in the collection.
  298. Adds "add to collection" and "remove from collection" handling to
  299. the method. The decorator argument indicates which method argument
  300. holds the SQLAlchemy-relevant value to be added, and return value, if
  301. any will be considered the value to remove.
  302. Arguments can be specified positionally (i.e. integer) or by name::
  303. @collection.replaces(2)
  304. def __setitem__(self, index, item): ...
  305. """
  306. def decorator(fn):
  307. fn._sa_instrument_before = ("fire_append_event", arg)
  308. fn._sa_instrument_after = "fire_remove_event"
  309. return fn
  310. return decorator
  311. @staticmethod
  312. def removes(arg):
  313. """Mark the method as removing an entity in the collection.
  314. Adds "remove from collection" handling to the method. The decorator
  315. argument indicates which method argument holds the SQLAlchemy-relevant
  316. value to be removed. Arguments can be specified positionally (i.e.
  317. integer) or by name::
  318. @collection.removes(1)
  319. def zap(self, item): ...
  320. For methods where the value to remove is not known at call-time, use
  321. collection.removes_return.
  322. """
  323. def decorator(fn):
  324. fn._sa_instrument_before = ("fire_remove_event", arg)
  325. return fn
  326. return decorator
  327. @staticmethod
  328. def removes_return():
  329. """Mark the method as removing an entity in the collection.
  330. Adds "remove from collection" handling to the method. The return
  331. value of the method, if any, is considered the value to remove. The
  332. method arguments are not inspected::
  333. @collection.removes_return()
  334. def pop(self): ...
  335. For methods where the value to remove is known at call-time, use
  336. collection.remove.
  337. """
  338. def decorator(fn):
  339. fn._sa_instrument_after = "fire_remove_event"
  340. return fn
  341. return decorator
  342. if TYPE_CHECKING:
  343. def collection_adapter(collection: Collection[Any]) -> CollectionAdapter:
  344. """Fetch the :class:`.CollectionAdapter` for a collection."""
  345. else:
  346. collection_adapter = operator.attrgetter("_sa_adapter")
  347. class CollectionAdapter:
  348. """Bridges between the ORM and arbitrary Python collections.
  349. Proxies base-level collection operations (append, remove, iterate)
  350. to the underlying Python collection, and emits add/remove events for
  351. entities entering or leaving the collection.
  352. The ORM uses :class:`.CollectionAdapter` exclusively for interaction with
  353. entity collections.
  354. """
  355. __slots__ = (
  356. "attr",
  357. "_key",
  358. "_data",
  359. "owner_state",
  360. "_converter",
  361. "invalidated",
  362. "empty",
  363. )
  364. attr: CollectionAttributeImpl
  365. _key: str
  366. # this is actually a weakref; see note in constructor
  367. _data: Callable[..., _AdaptedCollectionProtocol]
  368. owner_state: InstanceState[Any]
  369. _converter: _CollectionConverterProtocol
  370. invalidated: bool
  371. empty: bool
  372. def __init__(
  373. self,
  374. attr: CollectionAttributeImpl,
  375. owner_state: InstanceState[Any],
  376. data: _AdaptedCollectionProtocol,
  377. ):
  378. self.attr = attr
  379. self._key = attr.key
  380. # this weakref stays referenced throughout the lifespan of
  381. # CollectionAdapter. so while the weakref can return None, this
  382. # is realistically only during garbage collection of this object, so
  383. # we type this as a callable that returns _AdaptedCollectionProtocol
  384. # in all cases.
  385. self._data = weakref.ref(data) # type: ignore
  386. self.owner_state = owner_state
  387. data._sa_adapter = self
  388. self._converter = data._sa_converter
  389. self.invalidated = False
  390. self.empty = False
  391. def _warn_invalidated(self) -> None:
  392. util.warn("This collection has been invalidated.")
  393. @property
  394. def data(self) -> _AdaptedCollectionProtocol:
  395. "The entity collection being adapted."
  396. return self._data()
  397. @property
  398. def _referenced_by_owner(self) -> bool:
  399. """return True if the owner state still refers to this collection.
  400. This will return False within a bulk replace operation,
  401. where this collection is the one being replaced.
  402. """
  403. return self.owner_state.dict[self._key] is self._data()
  404. def bulk_appender(self):
  405. return self._data()._sa_appender
  406. def append_with_event(
  407. self, item: Any, initiator: Optional[AttributeEventToken] = None
  408. ) -> None:
  409. """Add an entity to the collection, firing mutation events."""
  410. self._data()._sa_appender(item, _sa_initiator=initiator)
  411. def _set_empty(self, user_data):
  412. assert (
  413. not self.empty
  414. ), "This collection adapter is already in the 'empty' state"
  415. self.empty = True
  416. self.owner_state._empty_collections[self._key] = user_data
  417. def _reset_empty(self) -> None:
  418. assert (
  419. self.empty
  420. ), "This collection adapter is not in the 'empty' state"
  421. self.empty = False
  422. self.owner_state.dict[self._key] = (
  423. self.owner_state._empty_collections.pop(self._key)
  424. )
  425. def _refuse_empty(self) -> NoReturn:
  426. raise sa_exc.InvalidRequestError(
  427. "This is a special 'empty' collection which cannot accommodate "
  428. "internal mutation operations"
  429. )
  430. def append_without_event(self, item: Any) -> None:
  431. """Add or restore an entity to the collection, firing no events."""
  432. if self.empty:
  433. self._refuse_empty()
  434. self._data()._sa_appender(item, _sa_initiator=False)
  435. def append_multiple_without_event(self, items: Iterable[Any]) -> None:
  436. """Add or restore an entity to the collection, firing no events."""
  437. if self.empty:
  438. self._refuse_empty()
  439. appender = self._data()._sa_appender
  440. for item in items:
  441. appender(item, _sa_initiator=False)
  442. def bulk_remover(self):
  443. return self._data()._sa_remover
  444. def remove_with_event(
  445. self, item: Any, initiator: Optional[AttributeEventToken] = None
  446. ) -> None:
  447. """Remove an entity from the collection, firing mutation events."""
  448. self._data()._sa_remover(item, _sa_initiator=initiator)
  449. def remove_without_event(self, item: Any) -> None:
  450. """Remove an entity from the collection, firing no events."""
  451. if self.empty:
  452. self._refuse_empty()
  453. self._data()._sa_remover(item, _sa_initiator=False)
  454. def clear_with_event(
  455. self, initiator: Optional[AttributeEventToken] = None
  456. ) -> None:
  457. """Empty the collection, firing a mutation event for each entity."""
  458. if self.empty:
  459. self._refuse_empty()
  460. remover = self._data()._sa_remover
  461. for item in list(self):
  462. remover(item, _sa_initiator=initiator)
  463. def clear_without_event(self) -> None:
  464. """Empty the collection, firing no events."""
  465. if self.empty:
  466. self._refuse_empty()
  467. remover = self._data()._sa_remover
  468. for item in list(self):
  469. remover(item, _sa_initiator=False)
  470. def __iter__(self):
  471. """Iterate over entities in the collection."""
  472. return iter(self._data()._sa_iterator())
  473. def __len__(self):
  474. """Count entities in the collection."""
  475. return len(list(self._data()._sa_iterator()))
  476. def __bool__(self):
  477. return True
  478. def _fire_append_wo_mutation_event_bulk(
  479. self, items, initiator=None, key=NO_KEY
  480. ):
  481. if not items:
  482. return
  483. if initiator is not False:
  484. if self.invalidated:
  485. self._warn_invalidated()
  486. if self.empty:
  487. self._reset_empty()
  488. for item in items:
  489. self.attr.fire_append_wo_mutation_event(
  490. self.owner_state,
  491. self.owner_state.dict,
  492. item,
  493. initiator,
  494. key,
  495. )
  496. def fire_append_wo_mutation_event(self, item, initiator=None, key=NO_KEY):
  497. """Notify that a entity is entering the collection but is already
  498. present.
  499. Initiator is a token owned by the InstrumentedAttribute that
  500. initiated the membership mutation, and should be left as None
  501. unless you are passing along an initiator value from a chained
  502. operation.
  503. .. versionadded:: 1.4.15
  504. """
  505. if initiator is not False:
  506. if self.invalidated:
  507. self._warn_invalidated()
  508. if self.empty:
  509. self._reset_empty()
  510. return self.attr.fire_append_wo_mutation_event(
  511. self.owner_state, self.owner_state.dict, item, initiator, key
  512. )
  513. else:
  514. return item
  515. def fire_append_event(self, item, initiator=None, key=NO_KEY):
  516. """Notify that a entity has entered the collection.
  517. Initiator is a token owned by the InstrumentedAttribute that
  518. initiated the membership mutation, and should be left as None
  519. unless you are passing along an initiator value from a chained
  520. operation.
  521. """
  522. if initiator is not False:
  523. if self.invalidated:
  524. self._warn_invalidated()
  525. if self.empty:
  526. self._reset_empty()
  527. return self.attr.fire_append_event(
  528. self.owner_state, self.owner_state.dict, item, initiator, key
  529. )
  530. else:
  531. return item
  532. def _fire_remove_event_bulk(self, items, initiator=None, key=NO_KEY):
  533. if not items:
  534. return
  535. if initiator is not False:
  536. if self.invalidated:
  537. self._warn_invalidated()
  538. if self.empty:
  539. self._reset_empty()
  540. for item in items:
  541. self.attr.fire_remove_event(
  542. self.owner_state,
  543. self.owner_state.dict,
  544. item,
  545. initiator,
  546. key,
  547. )
  548. def fire_remove_event(self, item, initiator=None, key=NO_KEY):
  549. """Notify that a entity has been removed from the collection.
  550. Initiator is the InstrumentedAttribute that initiated the membership
  551. mutation, and should be left as None unless you are passing along
  552. an initiator value from a chained operation.
  553. """
  554. if initiator is not False:
  555. if self.invalidated:
  556. self._warn_invalidated()
  557. if self.empty:
  558. self._reset_empty()
  559. self.attr.fire_remove_event(
  560. self.owner_state, self.owner_state.dict, item, initiator, key
  561. )
  562. def fire_pre_remove_event(self, initiator=None, key=NO_KEY):
  563. """Notify that an entity is about to be removed from the collection.
  564. Only called if the entity cannot be removed after calling
  565. fire_remove_event().
  566. """
  567. if self.invalidated:
  568. self._warn_invalidated()
  569. self.attr.fire_pre_remove_event(
  570. self.owner_state,
  571. self.owner_state.dict,
  572. initiator=initiator,
  573. key=key,
  574. )
  575. def __getstate__(self):
  576. return {
  577. "key": self._key,
  578. "owner_state": self.owner_state,
  579. "owner_cls": self.owner_state.class_,
  580. "data": self.data,
  581. "invalidated": self.invalidated,
  582. "empty": self.empty,
  583. }
  584. def __setstate__(self, d):
  585. self._key = d["key"]
  586. self.owner_state = d["owner_state"]
  587. # see note in constructor regarding this type: ignore
  588. self._data = weakref.ref(d["data"]) # type: ignore
  589. self._converter = d["data"]._sa_converter
  590. d["data"]._sa_adapter = self
  591. self.invalidated = d["invalidated"]
  592. self.attr = getattr(d["owner_cls"], self._key).impl
  593. self.empty = d.get("empty", False)
  594. def bulk_replace(values, existing_adapter, new_adapter, initiator=None):
  595. """Load a new collection, firing events based on prior like membership.
  596. Appends instances in ``values`` onto the ``new_adapter``. Events will be
  597. fired for any instance not present in the ``existing_adapter``. Any
  598. instances in ``existing_adapter`` not present in ``values`` will have
  599. remove events fired upon them.
  600. :param values: An iterable of collection member instances
  601. :param existing_adapter: A :class:`.CollectionAdapter` of
  602. instances to be replaced
  603. :param new_adapter: An empty :class:`.CollectionAdapter`
  604. to load with ``values``
  605. """
  606. assert isinstance(values, list)
  607. idset = util.IdentitySet
  608. existing_idset = idset(existing_adapter or ())
  609. constants = existing_idset.intersection(values or ())
  610. additions = idset(values or ()).difference(constants)
  611. removals = existing_idset.difference(constants)
  612. appender = new_adapter.bulk_appender()
  613. for member in values or ():
  614. if member in additions:
  615. appender(member, _sa_initiator=initiator)
  616. elif member in constants:
  617. appender(member, _sa_initiator=False)
  618. if existing_adapter:
  619. existing_adapter._fire_append_wo_mutation_event_bulk(
  620. constants, initiator=initiator
  621. )
  622. existing_adapter._fire_remove_event_bulk(removals, initiator=initiator)
  623. def prepare_instrumentation(
  624. factory: Union[Type[Collection[Any]], _CollectionFactoryType],
  625. ) -> _CollectionFactoryType:
  626. """Prepare a callable for future use as a collection class factory.
  627. Given a collection class factory (either a type or no-arg callable),
  628. return another factory that will produce compatible instances when
  629. called.
  630. This function is responsible for converting collection_class=list
  631. into the run-time behavior of collection_class=InstrumentedList.
  632. """
  633. impl_factory: _CollectionFactoryType
  634. # Convert a builtin to 'Instrumented*'
  635. if factory in __canned_instrumentation:
  636. impl_factory = __canned_instrumentation[factory]
  637. else:
  638. impl_factory = cast(_CollectionFactoryType, factory)
  639. cls: Union[_CollectionFactoryType, Type[Collection[Any]]]
  640. # Create a specimen
  641. cls = type(impl_factory())
  642. # Did factory callable return a builtin?
  643. if cls in __canned_instrumentation:
  644. # if so, just convert.
  645. # in previous major releases, this codepath wasn't working and was
  646. # not covered by tests. prior to that it supplied a "wrapper"
  647. # function that would return the class, though the rationale for this
  648. # case is not known
  649. impl_factory = __canned_instrumentation[cls]
  650. cls = type(impl_factory())
  651. # Instrument the class if needed.
  652. if __instrumentation_mutex.acquire():
  653. try:
  654. if getattr(cls, "_sa_instrumented", None) != id(cls):
  655. _instrument_class(cls)
  656. finally:
  657. __instrumentation_mutex.release()
  658. return impl_factory
  659. def _instrument_class(cls):
  660. """Modify methods in a class and install instrumentation."""
  661. # In the normal call flow, a request for any of the 3 basic collection
  662. # types is transformed into one of our trivial subclasses
  663. # (e.g. InstrumentedList). Catch anything else that sneaks in here...
  664. if cls.__module__ == "__builtin__":
  665. raise sa_exc.ArgumentError(
  666. "Can not instrument a built-in type. Use a "
  667. "subclass, even a trivial one."
  668. )
  669. roles, methods = _locate_roles_and_methods(cls)
  670. _setup_canned_roles(cls, roles, methods)
  671. _assert_required_roles(cls, roles, methods)
  672. _set_collection_attributes(cls, roles, methods)
  673. def _locate_roles_and_methods(cls):
  674. """search for _sa_instrument_role-decorated methods in
  675. method resolution order, assign to roles.
  676. """
  677. roles: Dict[str, str] = {}
  678. methods: Dict[str, Tuple[Optional[str], Optional[int], Optional[str]]] = {}
  679. for supercls in cls.__mro__:
  680. for name, method in vars(supercls).items():
  681. if not callable(method):
  682. continue
  683. # note role declarations
  684. if hasattr(method, "_sa_instrument_role"):
  685. role = method._sa_instrument_role
  686. assert role in (
  687. "appender",
  688. "remover",
  689. "iterator",
  690. "converter",
  691. )
  692. roles.setdefault(role, name)
  693. # transfer instrumentation requests from decorated function
  694. # to the combined queue
  695. before: Optional[Tuple[str, int]] = None
  696. after: Optional[str] = None
  697. if hasattr(method, "_sa_instrument_before"):
  698. op, argument = method._sa_instrument_before
  699. assert op in ("fire_append_event", "fire_remove_event")
  700. before = op, argument
  701. if hasattr(method, "_sa_instrument_after"):
  702. op = method._sa_instrument_after
  703. assert op in ("fire_append_event", "fire_remove_event")
  704. after = op
  705. if before:
  706. methods[name] = before + (after,)
  707. elif after:
  708. methods[name] = None, None, after
  709. return roles, methods
  710. def _setup_canned_roles(cls, roles, methods):
  711. """see if this class has "canned" roles based on a known
  712. collection type (dict, set, list). Apply those roles
  713. as needed to the "roles" dictionary, and also
  714. prepare "decorator" methods
  715. """
  716. collection_type = util.duck_type_collection(cls)
  717. if collection_type in __interfaces:
  718. assert collection_type is not None
  719. canned_roles, decorators = __interfaces[collection_type]
  720. for role, name in canned_roles.items():
  721. roles.setdefault(role, name)
  722. # apply ABC auto-decoration to methods that need it
  723. for method, decorator in decorators.items():
  724. fn = getattr(cls, method, None)
  725. if (
  726. fn
  727. and method not in methods
  728. and not hasattr(fn, "_sa_instrumented")
  729. ):
  730. setattr(cls, method, decorator(fn))
  731. def _assert_required_roles(cls, roles, methods):
  732. """ensure all roles are present, and apply implicit instrumentation if
  733. needed
  734. """
  735. if "appender" not in roles or not hasattr(cls, roles["appender"]):
  736. raise sa_exc.ArgumentError(
  737. "Type %s must elect an appender method to be "
  738. "a collection class" % cls.__name__
  739. )
  740. elif roles["appender"] not in methods and not hasattr(
  741. getattr(cls, roles["appender"]), "_sa_instrumented"
  742. ):
  743. methods[roles["appender"]] = ("fire_append_event", 1, None)
  744. if "remover" not in roles or not hasattr(cls, roles["remover"]):
  745. raise sa_exc.ArgumentError(
  746. "Type %s must elect a remover method to be "
  747. "a collection class" % cls.__name__
  748. )
  749. elif roles["remover"] not in methods and not hasattr(
  750. getattr(cls, roles["remover"]), "_sa_instrumented"
  751. ):
  752. methods[roles["remover"]] = ("fire_remove_event", 1, None)
  753. if "iterator" not in roles or not hasattr(cls, roles["iterator"]):
  754. raise sa_exc.ArgumentError(
  755. "Type %s must elect an iterator method to be "
  756. "a collection class" % cls.__name__
  757. )
  758. def _set_collection_attributes(cls, roles, methods):
  759. """apply ad-hoc instrumentation from decorators, class-level defaults
  760. and implicit role declarations
  761. """
  762. for method_name, (before, argument, after) in methods.items():
  763. setattr(
  764. cls,
  765. method_name,
  766. _instrument_membership_mutator(
  767. getattr(cls, method_name), before, argument, after
  768. ),
  769. )
  770. # intern the role map
  771. for role, method_name in roles.items():
  772. setattr(cls, "_sa_%s" % role, getattr(cls, method_name))
  773. cls._sa_adapter = None
  774. if not hasattr(cls, "_sa_converter"):
  775. cls._sa_converter = None
  776. cls._sa_instrumented = id(cls)
  777. def _instrument_membership_mutator(method, before, argument, after):
  778. """Route method args and/or return value through the collection
  779. adapter."""
  780. # This isn't smart enough to handle @adds(1) for 'def fn(self, (a, b))'
  781. if before:
  782. fn_args = list(
  783. util.flatten_iterator(inspect_getfullargspec(method)[0])
  784. )
  785. if isinstance(argument, int):
  786. pos_arg = argument
  787. named_arg = len(fn_args) > argument and fn_args[argument] or None
  788. else:
  789. if argument in fn_args:
  790. pos_arg = fn_args.index(argument)
  791. else:
  792. pos_arg = None
  793. named_arg = argument
  794. del fn_args
  795. def wrapper(*args, **kw):
  796. if before:
  797. if pos_arg is None:
  798. if named_arg not in kw:
  799. raise sa_exc.ArgumentError(
  800. "Missing argument %s" % argument
  801. )
  802. value = kw[named_arg]
  803. else:
  804. if len(args) > pos_arg:
  805. value = args[pos_arg]
  806. elif named_arg in kw:
  807. value = kw[named_arg]
  808. else:
  809. raise sa_exc.ArgumentError(
  810. "Missing argument %s" % argument
  811. )
  812. initiator = kw.pop("_sa_initiator", None)
  813. if initiator is False:
  814. executor = None
  815. else:
  816. executor = args[0]._sa_adapter
  817. if before and executor:
  818. getattr(executor, before)(value, initiator)
  819. if not after or not executor:
  820. return method(*args, **kw)
  821. else:
  822. res = method(*args, **kw)
  823. if res is not None:
  824. getattr(executor, after)(res, initiator)
  825. return res
  826. wrapper._sa_instrumented = True # type: ignore[attr-defined]
  827. if hasattr(method, "_sa_instrument_role"):
  828. wrapper._sa_instrument_role = method._sa_instrument_role # type: ignore[attr-defined] # noqa: E501
  829. wrapper.__name__ = method.__name__
  830. wrapper.__doc__ = method.__doc__
  831. return wrapper
  832. def __set_wo_mutation(collection, item, _sa_initiator=None):
  833. """Run set wo mutation events.
  834. The collection is not mutated.
  835. """
  836. if _sa_initiator is not False:
  837. executor = collection._sa_adapter
  838. if executor:
  839. executor.fire_append_wo_mutation_event(
  840. item, _sa_initiator, key=None
  841. )
  842. def __set(collection, item, _sa_initiator, key):
  843. """Run set events.
  844. This event always occurs before the collection is actually mutated.
  845. """
  846. if _sa_initiator is not False:
  847. executor = collection._sa_adapter
  848. if executor:
  849. item = executor.fire_append_event(item, _sa_initiator, key=key)
  850. return item
  851. def __del(collection, item, _sa_initiator, key):
  852. """Run del events.
  853. This event occurs before the collection is actually mutated, *except*
  854. in the case of a pop operation, in which case it occurs afterwards.
  855. For pop operations, the __before_pop hook is called before the
  856. operation occurs.
  857. """
  858. if _sa_initiator is not False:
  859. executor = collection._sa_adapter
  860. if executor:
  861. executor.fire_remove_event(item, _sa_initiator, key=key)
  862. def __before_pop(collection, _sa_initiator=None):
  863. """An event which occurs on a before a pop() operation occurs."""
  864. executor = collection._sa_adapter
  865. if executor:
  866. executor.fire_pre_remove_event(_sa_initiator)
  867. def _list_decorators() -> Dict[str, Callable[[_FN], _FN]]:
  868. """Tailored instrumentation wrappers for any list-like class."""
  869. def _tidy(fn):
  870. fn._sa_instrumented = True
  871. fn.__doc__ = getattr(list, fn.__name__).__doc__
  872. def append(fn):
  873. def append(self, item, _sa_initiator=None):
  874. item = __set(self, item, _sa_initiator, NO_KEY)
  875. fn(self, item)
  876. _tidy(append)
  877. return append
  878. def remove(fn):
  879. def remove(self, value, _sa_initiator=None):
  880. __del(self, value, _sa_initiator, NO_KEY)
  881. # testlib.pragma exempt:__eq__
  882. fn(self, value)
  883. _tidy(remove)
  884. return remove
  885. def insert(fn):
  886. def insert(self, index, value):
  887. value = __set(self, value, None, index)
  888. fn(self, index, value)
  889. _tidy(insert)
  890. return insert
  891. def __setitem__(fn):
  892. def __setitem__(self, index, value):
  893. if not isinstance(index, slice):
  894. existing = self[index]
  895. if existing is not None:
  896. __del(self, existing, None, index)
  897. value = __set(self, value, None, index)
  898. fn(self, index, value)
  899. else:
  900. # slice assignment requires __delitem__, insert, __len__
  901. step = index.step or 1
  902. start = index.start or 0
  903. if start < 0:
  904. start += len(self)
  905. if index.stop is not None:
  906. stop = index.stop
  907. else:
  908. stop = len(self)
  909. if stop < 0:
  910. stop += len(self)
  911. if step == 1:
  912. if value is self:
  913. return
  914. for i in range(start, stop, step):
  915. if len(self) > start:
  916. del self[start]
  917. for i, item in enumerate(value):
  918. self.insert(i + start, item)
  919. else:
  920. rng = list(range(start, stop, step))
  921. if len(value) != len(rng):
  922. raise ValueError(
  923. "attempt to assign sequence of size %s to "
  924. "extended slice of size %s"
  925. % (len(value), len(rng))
  926. )
  927. for i, item in zip(rng, value):
  928. self.__setitem__(i, item)
  929. _tidy(__setitem__)
  930. return __setitem__
  931. def __delitem__(fn):
  932. def __delitem__(self, index):
  933. if not isinstance(index, slice):
  934. item = self[index]
  935. __del(self, item, None, index)
  936. fn(self, index)
  937. else:
  938. # slice deletion requires __getslice__ and a slice-groking
  939. # __getitem__ for stepped deletion
  940. # note: not breaking this into atomic dels
  941. for item in self[index]:
  942. __del(self, item, None, index)
  943. fn(self, index)
  944. _tidy(__delitem__)
  945. return __delitem__
  946. def extend(fn):
  947. def extend(self, iterable):
  948. for value in list(iterable):
  949. self.append(value)
  950. _tidy(extend)
  951. return extend
  952. def __iadd__(fn):
  953. def __iadd__(self, iterable):
  954. # list.__iadd__ takes any iterable and seems to let TypeError
  955. # raise as-is instead of returning NotImplemented
  956. for value in list(iterable):
  957. self.append(value)
  958. return self
  959. _tidy(__iadd__)
  960. return __iadd__
  961. def pop(fn):
  962. def pop(self, index=-1):
  963. __before_pop(self)
  964. item = fn(self, index)
  965. __del(self, item, None, index)
  966. return item
  967. _tidy(pop)
  968. return pop
  969. def clear(fn):
  970. def clear(self, index=-1):
  971. for item in self:
  972. __del(self, item, None, index)
  973. fn(self)
  974. _tidy(clear)
  975. return clear
  976. # __imul__ : not wrapping this. all members of the collection are already
  977. # present, so no need to fire appends... wrapping it with an explicit
  978. # decorator is still possible, so events on *= can be had if they're
  979. # desired. hard to imagine a use case for __imul__, though.
  980. l = locals().copy()
  981. l.pop("_tidy")
  982. return l
  983. def _dict_decorators() -> Dict[str, Callable[[_FN], _FN]]:
  984. """Tailored instrumentation wrappers for any dict-like mapping class."""
  985. def _tidy(fn):
  986. fn._sa_instrumented = True
  987. fn.__doc__ = getattr(dict, fn.__name__).__doc__
  988. def __setitem__(fn):
  989. def __setitem__(self, key, value, _sa_initiator=None):
  990. if key in self:
  991. __del(self, self[key], _sa_initiator, key)
  992. value = __set(self, value, _sa_initiator, key)
  993. fn(self, key, value)
  994. _tidy(__setitem__)
  995. return __setitem__
  996. def __delitem__(fn):
  997. def __delitem__(self, key, _sa_initiator=None):
  998. if key in self:
  999. __del(self, self[key], _sa_initiator, key)
  1000. fn(self, key)
  1001. _tidy(__delitem__)
  1002. return __delitem__
  1003. def clear(fn):
  1004. def clear(self):
  1005. for key in self:
  1006. __del(self, self[key], None, key)
  1007. fn(self)
  1008. _tidy(clear)
  1009. return clear
  1010. def pop(fn):
  1011. def pop(self, key, default=NO_ARG):
  1012. __before_pop(self)
  1013. _to_del = key in self
  1014. if default is NO_ARG:
  1015. item = fn(self, key)
  1016. else:
  1017. item = fn(self, key, default)
  1018. if _to_del:
  1019. __del(self, item, None, key)
  1020. return item
  1021. _tidy(pop)
  1022. return pop
  1023. def popitem(fn):
  1024. def popitem(self):
  1025. __before_pop(self)
  1026. item = fn(self)
  1027. __del(self, item[1], None, 1)
  1028. return item
  1029. _tidy(popitem)
  1030. return popitem
  1031. def setdefault(fn):
  1032. def setdefault(self, key, default=None):
  1033. if key not in self:
  1034. self.__setitem__(key, default)
  1035. return default
  1036. else:
  1037. value = self.__getitem__(key)
  1038. if value is default:
  1039. __set_wo_mutation(self, value, None)
  1040. return value
  1041. _tidy(setdefault)
  1042. return setdefault
  1043. def update(fn):
  1044. def update(self, __other=NO_ARG, **kw):
  1045. if __other is not NO_ARG:
  1046. if hasattr(__other, "keys"):
  1047. for key in list(__other):
  1048. if key not in self or self[key] is not __other[key]:
  1049. self[key] = __other[key]
  1050. else:
  1051. __set_wo_mutation(self, __other[key], None)
  1052. else:
  1053. for key, value in __other:
  1054. if key not in self or self[key] is not value:
  1055. self[key] = value
  1056. else:
  1057. __set_wo_mutation(self, value, None)
  1058. for key in kw:
  1059. if key not in self or self[key] is not kw[key]:
  1060. self[key] = kw[key]
  1061. else:
  1062. __set_wo_mutation(self, kw[key], None)
  1063. _tidy(update)
  1064. return update
  1065. l = locals().copy()
  1066. l.pop("_tidy")
  1067. return l
  1068. _set_binop_bases = (set, frozenset)
  1069. def _set_binops_check_strict(self: Any, obj: Any) -> bool:
  1070. """Allow only set, frozenset and self.__class__-derived
  1071. objects in binops."""
  1072. return isinstance(obj, _set_binop_bases + (self.__class__,))
  1073. def _set_binops_check_loose(self: Any, obj: Any) -> bool:
  1074. """Allow anything set-like to participate in set binops."""
  1075. return (
  1076. isinstance(obj, _set_binop_bases + (self.__class__,))
  1077. or util.duck_type_collection(obj) == set
  1078. )
  1079. def _set_decorators() -> Dict[str, Callable[[_FN], _FN]]:
  1080. """Tailored instrumentation wrappers for any set-like class."""
  1081. def _tidy(fn):
  1082. fn._sa_instrumented = True
  1083. fn.__doc__ = getattr(set, fn.__name__).__doc__
  1084. def add(fn):
  1085. def add(self, value, _sa_initiator=None):
  1086. if value not in self:
  1087. value = __set(self, value, _sa_initiator, NO_KEY)
  1088. else:
  1089. __set_wo_mutation(self, value, _sa_initiator)
  1090. # testlib.pragma exempt:__hash__
  1091. fn(self, value)
  1092. _tidy(add)
  1093. return add
  1094. def discard(fn):
  1095. def discard(self, value, _sa_initiator=None):
  1096. # testlib.pragma exempt:__hash__
  1097. if value in self:
  1098. __del(self, value, _sa_initiator, NO_KEY)
  1099. # testlib.pragma exempt:__hash__
  1100. fn(self, value)
  1101. _tidy(discard)
  1102. return discard
  1103. def remove(fn):
  1104. def remove(self, value, _sa_initiator=None):
  1105. # testlib.pragma exempt:__hash__
  1106. if value in self:
  1107. __del(self, value, _sa_initiator, NO_KEY)
  1108. # testlib.pragma exempt:__hash__
  1109. fn(self, value)
  1110. _tidy(remove)
  1111. return remove
  1112. def pop(fn):
  1113. def pop(self):
  1114. __before_pop(self)
  1115. item = fn(self)
  1116. # for set in particular, we have no way to access the item
  1117. # that will be popped before pop is called.
  1118. __del(self, item, None, NO_KEY)
  1119. return item
  1120. _tidy(pop)
  1121. return pop
  1122. def clear(fn):
  1123. def clear(self):
  1124. for item in list(self):
  1125. self.remove(item)
  1126. _tidy(clear)
  1127. return clear
  1128. def update(fn):
  1129. def update(self, value):
  1130. for item in value:
  1131. self.add(item)
  1132. _tidy(update)
  1133. return update
  1134. def __ior__(fn):
  1135. def __ior__(self, value):
  1136. if not _set_binops_check_strict(self, value):
  1137. return NotImplemented
  1138. for item in value:
  1139. self.add(item)
  1140. return self
  1141. _tidy(__ior__)
  1142. return __ior__
  1143. def difference_update(fn):
  1144. def difference_update(self, value):
  1145. for item in value:
  1146. self.discard(item)
  1147. _tidy(difference_update)
  1148. return difference_update
  1149. def __isub__(fn):
  1150. def __isub__(self, value):
  1151. if not _set_binops_check_strict(self, value):
  1152. return NotImplemented
  1153. for item in value:
  1154. self.discard(item)
  1155. return self
  1156. _tidy(__isub__)
  1157. return __isub__
  1158. def intersection_update(fn):
  1159. def intersection_update(self, other):
  1160. want, have = self.intersection(other), set(self)
  1161. remove, add = have - want, want - have
  1162. for item in remove:
  1163. self.remove(item)
  1164. for item in add:
  1165. self.add(item)
  1166. _tidy(intersection_update)
  1167. return intersection_update
  1168. def __iand__(fn):
  1169. def __iand__(self, other):
  1170. if not _set_binops_check_strict(self, other):
  1171. return NotImplemented
  1172. want, have = self.intersection(other), set(self)
  1173. remove, add = have - want, want - have
  1174. for item in remove:
  1175. self.remove(item)
  1176. for item in add:
  1177. self.add(item)
  1178. return self
  1179. _tidy(__iand__)
  1180. return __iand__
  1181. def symmetric_difference_update(fn):
  1182. def symmetric_difference_update(self, other):
  1183. want, have = self.symmetric_difference(other), set(self)
  1184. remove, add = have - want, want - have
  1185. for item in remove:
  1186. self.remove(item)
  1187. for item in add:
  1188. self.add(item)
  1189. _tidy(symmetric_difference_update)
  1190. return symmetric_difference_update
  1191. def __ixor__(fn):
  1192. def __ixor__(self, other):
  1193. if not _set_binops_check_strict(self, other):
  1194. return NotImplemented
  1195. want, have = self.symmetric_difference(other), set(self)
  1196. remove, add = have - want, want - have
  1197. for item in remove:
  1198. self.remove(item)
  1199. for item in add:
  1200. self.add(item)
  1201. return self
  1202. _tidy(__ixor__)
  1203. return __ixor__
  1204. l = locals().copy()
  1205. l.pop("_tidy")
  1206. return l
  1207. class InstrumentedList(List[_T]):
  1208. """An instrumented version of the built-in list."""
  1209. class InstrumentedSet(Set[_T]):
  1210. """An instrumented version of the built-in set."""
  1211. class InstrumentedDict(Dict[_KT, _VT]):
  1212. """An instrumented version of the built-in dict."""
  1213. __canned_instrumentation: util.immutabledict[Any, _CollectionFactoryType] = (
  1214. util.immutabledict(
  1215. {
  1216. list: InstrumentedList,
  1217. set: InstrumentedSet,
  1218. dict: InstrumentedDict,
  1219. }
  1220. )
  1221. )
  1222. __interfaces: util.immutabledict[
  1223. Any,
  1224. Tuple[
  1225. Dict[str, str],
  1226. Dict[str, Callable[..., Any]],
  1227. ],
  1228. ] = util.immutabledict(
  1229. {
  1230. list: (
  1231. {
  1232. "appender": "append",
  1233. "remover": "remove",
  1234. "iterator": "__iter__",
  1235. },
  1236. _list_decorators(),
  1237. ),
  1238. set: (
  1239. {"appender": "add", "remover": "remove", "iterator": "__iter__"},
  1240. _set_decorators(),
  1241. ),
  1242. # decorators are required for dicts and object collections.
  1243. dict: ({"iterator": "values"}, _dict_decorators()),
  1244. }
  1245. )
  1246. def __go(lcls):
  1247. global keyfunc_mapping, mapped_collection
  1248. global column_keyed_dict, column_mapped_collection
  1249. global MappedCollection, KeyFuncDict
  1250. global attribute_keyed_dict, attribute_mapped_collection
  1251. from .mapped_collection import keyfunc_mapping
  1252. from .mapped_collection import column_keyed_dict
  1253. from .mapped_collection import attribute_keyed_dict
  1254. from .mapped_collection import KeyFuncDict
  1255. from .mapped_collection import mapped_collection
  1256. from .mapped_collection import column_mapped_collection
  1257. from .mapped_collection import attribute_mapped_collection
  1258. from .mapped_collection import MappedCollection
  1259. # ensure instrumentation is associated with
  1260. # these built-in classes; if a user-defined class
  1261. # subclasses these and uses @internally_instrumented,
  1262. # the superclass is otherwise not instrumented.
  1263. # see [ticket:2406].
  1264. _instrument_class(InstrumentedList)
  1265. _instrument_class(InstrumentedSet)
  1266. _instrument_class(KeyFuncDict)
  1267. __go(locals())