collections.py 51 KB

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