collections.py 53 KB

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