U aa@s\dZddlZddlZddlmZddlmZddlmZddlm Z dd l m Z dd l m Z dd l m Z d d dddgZe jZGdddeZGdddeZGdddeZddZGdddeZddZddZGdd d eZedZGdddeZdTd d!Zd"d#Zd$d%Z d&d'Z!d(d)Z"d*d+Z#d,d-Z$d.d/Z%d0d1Z&dUd2d3Z'dVd4d5Z(dWd6d7Z)dXd8d9Z*d:d;Z+dd?Z0d@dAZ1dBdCZ2GdDdEdEe3Z4GdFdGdGe-Z5GdHdIdIe6Z7e3e4e-e5e6e7iZ8e3dJdKdLdMe+fe-dNdKdLdMe2fe6e j9r dOdPie,fn dOdQie,fiZ:GdRdSdSe6Z;e!e;e!e4e!e5dS)YaNSupport for collections of mapped entities. The collections package supplies the machinery used to inform the ORM of collection membership changes. An instrumentation via decoration approach is used, allowing arbitrary types (including built-ins) to be used as entity collections without requiring inheritance from a base class. Instrumentation decoration relays membership change events to the :class:`.CollectionAttributeImpl` that is currently managing the collection. The decorators observe function call arguments and return values, tracking entities entering or leaving the collection. Two decorator approaches are provided. One is a bundle of generic decorators that map function arguments and return values to events:: from sqlalchemy.orm.collections import collection class MyClass(object): # ... @collection.adds(1) def store(self, item): self.data.append(item) @collection.removes_return() def pop(self): return self.data.pop() The second approach is a bundle of targeted decorators that wrap appropriate append and remove notifiers around the mutation methods present in the standard Python ``list``, ``set`` and ``dict`` interfaces. These could be specified in terms of generic decorator recipes, but are instead hand-tooled for increased efficiency. The targeted decorators occasionally implement adapter-like behavior, such as mapping bulk-set methods (``extend``, ``update``, ``__setslice__``, etc.) into the series of atomic mutation events that the ORM requires. The targeted decorators are used internally for automatic instrumentation of entity collection classes. Every collection class goes through a transformation process roughly like so: 1. If the class is a built-in, substitute a trivial sub-class 2. Is this class already instrumented? 3. Add in generic decorators 4. Sniff out the collection interface through duck-typing 5. Add targeted decoration to any undecorated interface method This process modifies the class at runtime, decorating methods and adding some bookkeeping properties. This isn't possible (or desirable) for built-in classes like ``list``, so trivial sub-classes are substituted to hold decoration:: class InstrumentedList(list): pass Collection classes can be specified in ``relationship(collection_class=)`` as types or a function that returns an instance. Collection classes are inspected and instrumented during the mapper compilation phase. The collection_class callable will be executed once to produce a specimen instance, and the type of that specimen will be instrumented. Functions that return built-in types like ``lists`` will be adapted to produce instrumented instances. When extending a known type like ``list``, additional decorations are not generally not needed. Odds are, the extension method will delegate to a method that's already instrumented. For example:: class QueueIsh(list): def push(self, item): self.append(item) def shift(self): return self.pop(0) There's no need to decorate these methods. ``append`` and ``pop`` are already instrumented as part of the ``list`` interface. Decorating them would fire duplicate events, which should be avoided. The targeted decoration tries not to rely on other methods in the underlying collection class, but some are unavoidable. Many depend on 'read' methods being present to properly instrument a 'write', for example, ``__setitem__`` needs ``__getitem__``. "Bulk" methods like ``update`` and ``extend`` may also reimplemented in terms of atomic appends and removes, so the ``extend`` decoration will actually perform many ``append`` operations and not call the underlying method at all. Tight control over bulk operation and the firing of events is also possible by implementing the instrumentation internally in your methods. The basic instrumentation package works under the general assumption that collection mutation will not raise unusual exceptions. If you want to closely orchestrate append and remove events with exception management, internal instrumentation may be the answer. Within your method, ``collection_adapter(self)`` will retrieve an object that you can use for explicit control over triggering append and remove events. The owning object and :class:`.CollectionAttributeImpl` are also reachable through the adapter, allowing for some very sophisticated behavior. N)inspect_getfullargspec)base)exc)util) coercions) expression)roles collectioncollection_adaptermapped_collectioncolumn_mapped_collectionattribute_mapped_collectionc@s0eZdZdZddZddZddZdd Zd S) _PlainColumnGetterzPlain column getter, stores collection of Column objects directly. Serializes to a :class:`._SerializableColumnGetterV2` which has more expensive __call__() performance and some rare caveats. cCs||_t|dk|_dSNr)colslen composite)selfrr[C:\Users\vtejo\AppData\Local\Temp\pip-unpacked-wheel-nyjtotrf\sqlalchemy\orm\collections.py__init__sz_PlainColumnGetter.__init__cCs t|jSN)_SerializableColumnGetterV2_reduce_from_colsrrrrr __reduce__sz_PlainColumnGetter.__reduce__cCs|jSr)r)rmapperrrr_colssz_PlainColumnGetter._colscsHt|tfdd|D}|jrsz/_PlainColumnGetter.__call__..r)rinstance_state _state_mapperrrtuplervaluekeyrr$r__call__s   z_PlainColumnGetter.__call__N)__name__ __module__ __qualname____doc__rrrr.rrrrrs  rc@s(eZdZdZddZddZddZdS) _SerializableColumnGetterzlColumn-based getter used in version 0.7.6 only. Remains here for pickle compatibility with 0.7.6. cCs||_t|dk|_dSrcolkeysrrrr5rrrrsz"_SerializableColumnGetter.__init__cCs t|jffSr)r3r5rrrrrsz$_SerializableColumnGetter.__reduce__csDt|tfdd|jD}|jr8t|S|dSdS)Ncs$g|]}jjj|qSr)r r!Z mapped_tablecolumns)r"kr$rrr's  z6_SerializableColumnGetter.__call__..r)rr(r)r5rr*r+rr$rr.s   z"_SerializableColumnGetter.__call__N)r/r0r1r2rrr.rrrrr3sr3c@s4eZdZdZddZddZeddZdd Zd S) ra<Updated serializable getter which deals with multi-table mapped classes. Two extremely unusual cases are not supported. Mappings which have tables across multiple metadata objects, or which are mapped to non-Table selectables linked across inheriting mappers may fail to function here. cCs||_t|dk|_dSrr4r6rrrrsz$_SerializableColumnGetterV2.__init__cCs|j|jffSr) __class__r5rrrrrsz&_SerializableColumnGetterV2.__reduce__cs$ddfdd|D}t|ffS)NcSst|jtjsdS|jjSdSr) isinstancetabler Z TableClauser-)crrr _table_keyszA_SerializableColumnGetterV2._reduce_from_cols.._table_keycsg|]}|j|fqSr)r-)r"r<r=rrr'szA_SerializableColumnGetterV2._reduce_from_cols..)r)clsrr5rr>rrsz-_SerializableColumnGetterV2._reduce_from_colscCshg}t|jdd}|jD]J\}}|dks8|dks8||krL||jj|q||j|j|q|S)Nmetadata)getattrZ local_tabler5appendr<Ztables)rrrr@ZckeyZtkeyrrrrsz!_SerializableColumnGetterV2._colsN) r/r0r1r2rr classmethodrrrrrrrs   rcs(ddt|D}t|fddS)aA dictionary-based collection type with column-based keying. Returns a :class:`.MappedCollection` factory with a keying function generated from mapping_spec, which may be a Column or a sequence of Columns. The key value must be immutable for the lifetime of the object. You can not, for example, map on foreign key values if those key values will change during the session, i.e. from None to a database-assigned integer after a session flush. cSsg|]}tjtj|ddqS) mapping_spec)argname)rexpectr ZColumnArgumentRole)r"qrrrr'sz,column_mapped_collection..cstSrMappedCollectionrkeyfuncrrz*column_mapped_collection..)rZto_listr)rDrrrJrrs c@s$eZdZddZddZddZdS)_SerializableAttrGettercCs||_t||_dSr)nameoperator attrgettergetter)rrOrrrrsz _SerializableAttrGetter.__init__cCs ||SrrR)rtargetrrrr.sz _SerializableAttrGetter.__call__cCs t|jffSr)rNrOrrrrrsz"_SerializableAttrGetter.__reduce__N)r/r0r1rr.rrrrrrNsrNcst|fddS)aA dictionary-based collection type with attribute-based keying. Returns a :class:`.MappedCollection` factory with a keying based on the 'attr_name' attribute of entities in the collection, where ``attr_name`` is the string name of the attribute. .. warning:: the key value must be assigned to its final value **before** it is accessed by the attribute mapped collection. Additionally, changes to the key attribute are **not tracked** automatically, which means the key in the dictionary is not automatically synchronized with the key value on the target object itself. See the section :ref:`key_collections_mutations` for an example. cstSrrHrrSrrrLrMz-attribute_mapped_collection..)rN) attr_namerrSrr scs fddS)aA dictionary-based collection type with arbitrary keying. Returns a :class:`.MappedCollection` factory with a keying function generated from keyfunc, a callable that takes an entity and returns a key value. The key value must be immutable for the lifetime of the object. You can not, for example, map on foreign key values if those key values will change during the session, i.e. from None to a database-assigned integer after a session flush. cstSrrHrrJrrrL+rMz#mapped_collection..rrJrrJrr s c@seZdZdZeddZeddZeddZedd Zee d d d d Z eddZ eddZ eddZeddZdS)r auDecorators for entity collection classes. The decorators fall into two groups: annotations and interception recipes. The annotating decorators (appender, remover, iterator, converter, internally_instrumented) indicate the method's purpose and take no arguments. They are not written with parens:: @collection.appender def append(self, append): ... The recipe decorators all require parens, even those that take no arguments:: @collection.adds('entity') def insert(self, position, entity): ... @collection.removes_return() def popitem(self): ... cCs d|_|S)aTag the method as the collection appender. The appender method is called with one positional argument: the value to append. The method will be automatically decorated with 'adds(1)' if not already decorated:: @collection.appender def add(self, append): ... # or, equivalently @collection.appender @collection.adds(1) def add(self, append): ... # for mapping type, an 'append' may kick out a previous value # that occupies that slot. consider d['a'] = 'foo'- any previous # value in d['a'] is discarded. @collection.appender @collection.replaces(1) def add(self, entity): key = some_key_func(entity) previous = None if key in self: previous = self[key] self[key] = entity return previous If the value to append is not allowed in the collection, you may raise an exception. Something to remember is that the appender will be called for each object mapped by a database query. If the database contains rows that violate your collection semantics, you will need to get creative to fix the problem, as access via the collection will not work. If the appender method is internally instrumented, you must also receive the keyword argument '_sa_initiator' and ensure its promulgation to collection events. appender_sa_instrument_rolefnrrrrVHs)zcollection.appendercCs d|_|S)aTag the method as the collection remover. The remover method is called with one positional argument: the value to remove. The method will be automatically decorated with :meth:`removes_return` if not already decorated:: @collection.remover def zap(self, entity): ... # or, equivalently @collection.remover @collection.removes_return() def zap(self, ): ... If the value to remove is not present in the collection, you may raise an exception or return None to ignore the error. If the remove method is internally instrumented, you must also receive the keyword argument '_sa_initiator' and ensure its promulgation to collection events. removerrWrYrrrr[tszcollection.removercCs d|_|S)zTag the method as the collection remover. The iterator method is called with no arguments. It is expected to return an iterator over all collection members:: @collection.iterator def __iter__(self): ... iteratorrWrYrrrr\s zcollection.iteratorcCs d|_|S)aTag the method as instrumented. This tag will prevent any decoration from being applied to the method. Use this if you are orchestrating your own calls to :func:`.collection_adapter` in one of the basic SQLAlchemy interface methods, or to prevent an automatic ABC method decoration from wrapping your implementation:: # normally an 'extend' method on a list-like class would be # automatically intercepted and re-implemented in terms of # SQLAlchemy events and append(). your implementation will # never be called, unless: @collection.internally_instrumented def extend(self, items): ... T)_sa_instrumentedrYrrrinternally_instrumentedsz"collection.internally_instrumentedz1.3zThe :meth:`.collection.converter` handler is deprecated and will be removed in a future release. Please refer to the :class:`.AttributeEvents.bulk_replace` listener interface in conjunction with the :func:`.event.listen` function.cCs d|_|S)aTag the method as the collection converter. This optional method will be called when a collection is being replaced entirely, as in:: myobj.acollection = [newvalue1, newvalue2] The converter method will receive the object being assigned and should return an iterable of values suitable for use by the ``appender`` method. A converter must not assign values or mutate the collection, its sole job is to adapt the value the user provides into an iterable of values for the ORM's use. The default converter implementation will use duck-typing to do the conversion. A dict-like collection will be convert into an iterable of dictionary values, and other types will simply be iterated:: @collection.converter def convert(self, other): ... If the duck-typing of the object does not match the type of this collection, a TypeError is raised. Supply an implementation of this method if you want to expand the range of possible types that can be assigned in bulk or perform validation on the values about to be assigned. converterrWrYrrrr_s%zcollection.convertercsfdd}|S)aMark the method as adding an entity to the collection. Adds "add to collection" handling to the method. The decorator argument indicates which method argument holds the SQLAlchemy-relevant value. Arguments can be specified positionally (i.e. integer) or by name:: @collection.adds(1) def push(self, item): ... @collection.adds('entity') def do_stuff(self, thing, entity=None): ... csdf|_|S)Nfire_append_event_sa_instrument_beforerYargrr decorators z"collection.adds..decoratorrrdrerrcraddss zcollection.addscsfdd}|S)aMark the method as replacing an entity in the collection. Adds "add to collection" and "remove from collection" handling to the method. The decorator argument indicates which method argument holds the SQLAlchemy-relevant value to be added, and return value, if any will be considered the value to remove. Arguments can be specified positionally (i.e. integer) or by name:: @collection.replaces(2) def __setitem__(self, index, item): ... csdf|_d|_|S)Nr`fire_remove_event)rb_sa_instrument_afterrYrcrrres z&collection.replaces..decoratorrrfrrcrreplacess zcollection.replacescsfdd}|S)aMark the method as removing an entity in the collection. Adds "remove from collection" handling to the method. The decorator argument indicates which method argument holds the SQLAlchemy-relevant value to be removed. Arguments can be specified positionally (i.e. integer) or by name:: @collection.removes(1) def zap(self, item): ... For methods where the value to remove is not known at call-time, use collection.removes_return. csdf|_|SNrhrarYrcrrres z%collection.removes..decoratorrrfrrcrremovess zcollection.removescCs dd}|S)aMark the method as removing an entity in the collection. Adds "remove from collection" handling to the method. The return value of the method, if any, is considered the value to remove. The method arguments are not inspected:: @collection.removes_return() def pop(self): ... For methods where the value to remove is known at call-time, use collection.remove. cSs d|_|Srk)rirYrrrre/sz,collection.removes_return..decoratorr)rerrrremoves_returnszcollection.removes_returnN)r/r0r1r2 staticmethodrVr[r\r^r deprecatedr_rgrjrlrmrrrrr .s. +        _sa_adapterc@seZdZdZdZddZddZeddZed d Z d d Z d6ddZ ddZ ddZ ddZddZddZddZd7ddZddZd8d d!Zd"d#Zd$d%Zd&d'Zd(d)ZeZd9d*d+Zd:d,d-Zd;d.d/Zd||_|j|_t||_||_||_|j|_ d|_ d|_ dS)NF) rrr-rsweakrefrefrtrurp _sa_converterrvrwrx)rrrrudatarrrrQs zCollectionAdapter.__init__cCstddS)Nz%This collection has been invalidated.)rwarnrrrr_warn_invalidated[sz#CollectionAdapter._warn_invalidatedcCs|S)z$The entity collection being adapted.)rtrrrrr|^szCollectionAdapter.datacCs|jj|j|kS)zreturn True if the owner state still refers to this collection. This will return False within a bulk replace operation, where this collection is the one being replaced. )rur!rsrtrrrr_referenced_by_ownercsz&CollectionAdapter._referenced_by_ownercCs |jSrrt _sa_appenderrrrr bulk_appendermszCollectionAdapter.bulk_appenderNcCs|j||ddS)z8Add an entity to the collection, firing mutation events. _sa_initiatorNrritem initiatorrrrappend_with_eventpsz#CollectionAdapter.append_with_eventcCs&|jrtdd|_||jj|j<dS)Nz7This collection adapter is already in the 'empty' stateT)rxAssertionErrorru_empty_collectionsrs)r user_datarrr _set_emptyus zCollectionAdapter._set_emptycCs2|jstdd|_|jj|j|jj|j<dS)Nz3This collection adapter is not in the 'empty' stateF)rxrrurpoprsr!rrrr _reset_empty|szCollectionAdapter._reset_emptycCstddS)NzZThis is a special 'empty' collection which cannot accommodate internal mutation operations)sa_excInvalidRequestErrorrrrr _refuse_emptyszCollectionAdapter._refuse_emptycCs$|jr||j|dddSz=Add or restore an entity to the collection, firing no events.FrNrxrrtrrrrrrappend_without_eventsz&CollectionAdapter.append_without_eventcCs2|jr||j}|D]}||ddqdSrr)ritemsrVrrrrappend_multiple_without_events  z/CollectionAdapter.append_multiple_without_eventcCs |jSrrt _sa_removerrrrr bulk_removerszCollectionAdapter.bulk_removercCs|j||ddS)z=Remove an entity from the collection, firing mutation events.rNrrrrrremove_with_eventsz#CollectionAdapter.remove_with_eventcCs$|jr||j|dddS)z7Remove an entity from the collection, firing no events.FrN)rxrrtrrrrrremove_without_eventsz&CollectionAdapter.remove_without_eventcCs6|jr||j}t|D]}|||dq dS)z>Empty the collection, firing a mutation event for each entity.rNrxrrtrlist)rrr[rrrrclear_with_events   z"CollectionAdapter.clear_with_eventcCs6|jr||j}t|D]}||ddq dS)z'Empty the collection, firing no events.FrNr)rr[rrrrclear_without_events   z%CollectionAdapter.clear_without_eventcCst|S)z(Iterate over entities in the collection.)iterrt _sa_iteratorrrrr__iter__szCollectionAdapter.__iter__cCstt|S)z!Count entities in the collection.)rrrtrrrrr__len__szCollectionAdapter.__len__cCsdSNTrrrrr__bool__szCollectionAdapter.__bool__cCsD|dk r<|jr||jr$||j|j|jj||S|SdS)abNotify that a entity is entering the collection but is already present. Initiator is a token owned by the InstrumentedAttribute that initiated the membership mutation, and should be left as None unless you are passing along an initiator value from a chained operation. .. versionadded:: 1.4.15 FN)rwr~rxrrrfire_append_wo_mutation_eventrur!rrrrrs z/CollectionAdapter.fire_append_wo_mutation_eventcCsD|dk r<|jr||jr$||j|j|jj||S|SdS)a Notify that a entity has entered the collection. Initiator is a token owned by the InstrumentedAttribute that initiated the membership mutation, and should be left as None unless you are passing along an initiator value from a chained operation. FN)rwr~rxrrrr`rur!rrrrr`s z#CollectionAdapter.fire_append_eventcCs@|dk r<|jr||jr$||j|j|jj||dS)aNotify that a entity has been removed from the collection. Initiator is the InstrumentedAttribute that initiated the membership mutation, and should be left as None unless you are passing along an initiator value from a chained operation. FN)rwr~rxrrrrhrur!rrrrrhsz#CollectionAdapter.fire_remove_eventcCs*|jr||jj|j|jj|ddS)zNotify that an entity is about to be removed from the collection. Only called if the entity cannot be removed after calling fire_remove_event(). rN)rwr~rrfire_pre_remove_eventrur!)rrrrrr sz'CollectionAdapter.fire_pre_remove_eventcCs |j|j|jj|j|j|jdS)N)r-ru owner_clsr|rwrx)rsruclass_r|rwrxrrrr __getstate__szCollectionAdapter.__getstate__cCsj|d|_|d|_t|d|_|dj|_||d_|d|_t |d|jj |_ | dd|_ dS)Nr-rur|rwrrxF)rsruryrzrtr{rvrprwrAimplrrgetrx)rdrrr __setstate__!s     zCollectionAdapter.__setstate__)N)N)N)N)N)N)N) r/r0r1r2 __slots__rr~propertyr|rrrrrrrrrrrrrrrr __nonzero__rr`rhrrrrrrrrq:s<               rqc Cst|tsttj}||pd}||p*d}||p6d|}||}|} |pXdD].} | |krt| | |dqZ| |krZ| | ddqZ|r|D]} |j| |dqdS)aFLoad a new collection, firing events based on prior like membership. Appends instances in ``values`` onto the ``new_adapter``. Events will be fired for any instance not present in the ``existing_adapter``. Any instances in ``existing_adapter`` not present in ``values`` will have remove events fired upon them. :param values: An iterable of collection member instances :param existing_adapter: A :class:`.CollectionAdapter` of instances to be replaced :param new_adapter: An empty :class:`.CollectionAdapter` to load with ``values`` rrFrN) r:rrrZ IdentitySet intersection differencerrh) valuesZexisting_adapterZ new_adapterrZidsetZexisting_idset constantsZ additionsZremovalsrVmemberrrr bulk_replace,s   rcCsj|tkrt|}t|}|tkr2t||}|}trfz t|ddt|krXt|W5tX|S)aoPrepare a callable for future use as a collection class factory. Given a collection class factory (either a type or no-arg callable), return another factory that will produce compatible instances when called. This function is responsible for converting collection_class=list into the run-time behavior of collection_class=InstrumentedList. r]N) __canned_instrumentationtype__converting_factory__instrumentation_mutexacquirereleaserAid_instrument_class)factoryr?rrrprepare_instrumentationTs     rcs.t|fdd}dj|_j|_|S)zsReturn a wrapper that converts a "canned" collection like set, dict, list into the Instrumented* version. cs}|Srr)r Zinstrumented_clsoriginal_factoryrrwrappersz%__converting_factory..wrapperz %sWrapper)rr/r2)Z specimen_clsrrrrrrws  rcCsH|jdkrtdt|\}}t|||t|||t|||dS)z6Modify methods in a class and install instrumentation. __builtin__zGCan not instrument a built-in type. Use a subclass, even a trivial one.N)r0r ArgumentError_locate_roles_and_methods_setup_canned_roles_assert_required_roles_set_collection_attributesr?r methodsrrrrs    rc Csi}i}|jD]}t|D]\}}t|s0qt|drX|j}|dksLt|||d\}}t|dr|j\} } | dkst| | f}t|dr|j } | dkst| }|r||f||<q|rdd|f||<qq||fS)zgsearch for _sa_instrument_role-decorated methods in method resolution order, assign to roles. rX)rVr[r\r_)NNrb)r`rhriN) __mro__varsrcallablehasattrrXr setdefaultrbri) r?r rZsuperclsrOmethodrolebeforeafteropargumentrrrrs0         rc Cst|}|tkrt|\}}|D]\}}|||q&|D]:\}} t||d} | rD||krDt| dsDt||| | qDdS)zsee if this class has "canned" roles based on a known collection type (dict, set, list). Apply those roles as needed to the "roles" dictionary, and also prepare "decorator" methods Nr])rduck_type_collection __interfacesrrrArsetattr) r?r rZcollection_typeZ canned_rolesZ decoratorsrrOrrerZrrrrs   rcCsd|kst||ds(td|jn,|d|krTtt||ddsTd||d<d|ksjt||ds|td|jn,|d|krtt||ddsd||d<d|kst||dstd |jd S) zTensure all roles are present, and apply implicit instrumentation if needed rVz>Type %s must elect an appender method to be a collection classr])r`rNr[zType %s must elect an iterator method to be a collection classN)rrrr/rArrrrrs8    rc Cs|D]*\}\}}}t||tt|||||q|D]\}}t|d|t||qdn|krV|nd~fdd}d|_t drj |_ j |_ j |_ |S)zIRoute method args and/or return value through the collection adapter.rNcsrbdkr,|kr"td|}n6t|krB|}n |krT|}ntd|dd}|dkr|d}n |dj}r|rt|||r|s||S||}|dk rt||||SdS)NzMissing argument %srFr)rrrrrprA)argskwr,rexecutorresrrrrZ named_argZpos_argrrr-s4        z/_instrument_membership_mutator..wrapperTrX) rrZflatten_iteratorrr:intrindexr]rrXr/r2)rrrrZfn_argsrrrrrs&  # rcCs"|dk r|j}|r|||dS)zERun set wo mutation events. The collection is not mutated. FN)rprr rrrrrr__set_wo_mutationXsrcCs"|dk r|j}|r|||}|S)z^Run set events. This event always occurs before the collection is actually mutated. F)rpr`rrrr__setds  rcCs"|dk r|j}|r|||dS)aRun del events. This event occurs before the collection is actually mutated, *except* in the case of a pop operation, in which case it occurs afterwards. For pop operations, the __before_pop hook is called before the operation occurs. FN)rprhrrrr__delrs rcCs|j}|r||dS)z;An event which occurs on a before a pop() operation occurs.N)rpr)r rrrrr __before_popsrc sddfdd}fdd}fdd}fd d }fd d }tjrbfd d}fdd}fdd}fdd}fdd} tjsfdd} t} | d| S)z:Tailored instrumentation wrappers for any list-like class.cSsd|_tt|jj|_dSr)r]rArr/r2rYrrr_tidysz_list_decorators.._tidycsdfdd }||S)Ncst|||}||dSrr)rrrrYrrrBs z0_list_decorators..append..append)Nr)rZrBrrYrrBsz _list_decorators..appendcsdfdd }||S)Ncst|||||dSrrrr,rrYrrremoves z0_list_decorators..remove..remove)NrrZrrrYrrsz _list_decorators..removecsfdd}||S)Ncst||}|||dSrr)rrr,rYrrinserts z0_list_decorators..insert..insertr)rZrrrYrrs z _list_decorators..insertcsfdd}||S)Nc sPt|ts>||}|dk r$t||t||}|||n|jpFd}|jpPd}|dkrf|t|7}|jdk rx|j}nt|}|dkr|t|7}|dkr||krdSt|||D]}t||kr||=qt |D]\}}| |||qn\t t|||} t|t| kr*t dt|t| ft | |D]\}}|||q4dS)NrrzBattempt to assign sequence of size %s to extended slice of size %s)r:slicerrstepstartrstoprange enumeraterr ValueErrorzip __setitem__) rrr,existingrrrirrngrYrrrs@         z:_list_decorators..__setitem__..__setitem__rrZrrrYrrs (z%_list_decorators..__setitem__csfdd}||S)NcsNt|ts(||}t||||n"||D]}t||q0||dSr)r:rrrrrrYrr __delitem__s     z:_list_decorators..__delitem__..__delitem__rrZrrrYrrs z%_list_decorators..__delitem__csfdd}||S)Ncs@||D]}t|q fdd|D}|||dS)Ncsg|]}t|qSrr)r"r,rrrr'szP_list_decorators..__setslice__..__setslice__..r)rrendrr,rYrr __setslice__s z<_list_decorators..__setslice__..__setslice__r)rZrrrYrrs z&_list_decorators..__setslice__csfdd}||S)Ncs,|||D]}t||q |||dSrr)rrrr,rYrr __delslice__s z<_list_decorators..__delslice__..__delslice__r)rZrrrYrrs z&_list_decorators..__delslice__csdd}||S)NcSs|D]}||qdSrrBriterabler,rrrextendsz0_list_decorators..extend..extendr)rZr rrrr sz _list_decorators..extendcsdd}||S)NcSs|D]}||q|Srrrrrr__iadd__s z4_list_decorators..__iadd__..__iadd__r)rZr rrrr sz"_list_decorators..__iadd__csdfdd }||S)Ncs t|||}t|||SrrrrrYrrrs  z*_list_decorators..pop..pop)r rrZrrrYrr sz_list_decorators..popcsdfdd }||S)Nr cs |D]}t||q|dSrrrrYrrclears z._list_decorators..clear..clear)r rrZrrrYrrsz_list_decorators..clearr)rZpy2klocalscopyr) rBrrrrrrr r rrlrrr_list_decoratorss"   ,      rcsddtdfdd}fdd}fdd }fd d }fd d }fdd}fdd}t}|d|d|S)zBTailored instrumentation wrappers for any dict-like mapping class.cSsd|_tt|jj|_dSr)r]rAr!r/r2rYrrrr/sz_dict_decorators.._tidy Unspecifiedcsdfdd }||S)Ncs4||krt||||t|||}|||dSr)rr)rr-r,rrYrrr6s z:_dict_decorators..__setitem__..__setitem__)NrrrrYrr5sz%_dict_decorators..__setitem__csdfdd }||S)Ncs&||krt||||||dSrr)rr-rrYrrr@sz:_dict_decorators..__delitem__..__delitem__)NrrrrYrr?sz%_dict_decorators..__delitem__csfdd}||S)Ncs$|D]}t|||q|dSrr)rr-rYrrrIsz._dict_decorators..clear..clearrrrrYrrHs z_dict_decorators..clearcsffdd }||S)NcsBt|||k}|kr$||}n |||}|r>t|||Srr )rr-defaultZ_to_delr)rrZrrrRs   z*_dict_decorators..pop..poprr rrrYrrQs z_dict_decorators..popcsfdd}||S)Ncs"t||}t||d|Srr rrYrrpopitemasz2_dict_decorators..popitem..popitemr)rZrrrYrr`s z!_dict_decorators..popitemcsddd}||S)NcSs>||kr||||S||}||kr6t||d|SdSr)r __getitem__r)rr-rr,rrrrks   z8_dict_decorators..setdefault..setdefault)Nr)rZrrrrrjs z$_dict_decorators..setdefaultcsffdd }||S)Ncs|k rt|drXt|D]:}||ks6||||k rD||||<qt|||dqn8|D]2\}}||ksx|||k r|||<q\t||dq\|D]:}||ks||||k r||||<qt|||dqdS)Nkeys)rrr)rZ__otherrr-r,)rrrupdatezs    z0_dict_decorators..update..updaterrZrrrrrysz _dict_decorators..updaterrsymbolrrr)rrrrrrrrrrr_dict_decorators,s      rcCst|t|jfS)zKAllow only set, frozenset and self.__class__-derived objects in binops.)r:_set_binop_basesr9robjrrr_set_binops_check_strictsr"cCs t|t|jfpt|tkS)z5Allow anything set-like to participate in set binops.)r:rr9rrsetr rrr_set_binops_check_looses r$csddtd}fdd}fdd}fdd }fd d }fd d }fdd}fdd}fdd}fdd} fdd} fdd} fdd} fdd} t}|d|d|S)z9Tailored instrumentation wrappers for any set-like class.cSsd|_tt|jj|_dSr)r]rAr#r/r2rYrrrrsz_set_decorators.._tidyrcsdfdd }||S)Ncs0||krt|||}n t|||||dSr)rrrrYrradds z)_set_decorators..add..add)Nr)rZr%rrYrr%sz_set_decorators..addcsdfdd }||S)Ncs"||krt|||||dSrrrrYrrdiscards z1_set_decorators..discard..discard)Nr)rZr&rrYrr&sz _set_decorators..discardcsdfdd }||S)Ncs"||krt|||||dSrrrrYrrrs z/_set_decorators..remove..remove)NrrrrYrrsz_set_decorators..removecsfdd}||S)Ncst||}t|||Srr rrYrrrs z)_set_decorators..pop..poprr rrYrrs z_set_decorators..popcsdd}||S)NcSst|D]}||qdSr)rrrrrrrs z-_set_decorators..clear..clearrrrrrrsz_set_decorators..clearcsdd}||S)NcSs|D]}||qdSr)r%rr,rrrrrsz/_set_decorators..update..updaterrrrrrsz_set_decorators..updatecsdd}||S)NcSs&t||stS|D]}||q|Sr)r"NotImplementedr%r'rrr__ior__s   z1_set_decorators..__ior__..__ior__r)rZr)rrrr)sz _set_decorators..__ior__csdd}||S)NcSs|D]}||qdSr)r&r'rrrdifference_updateszE_set_decorators..difference_update..difference_updater)rZr*rrrr*sz*_set_decorators..difference_updatecsdd}||S)NcSs&t||stS|D]}||q|Sr)r"r(r&r'rrr__isub__s   z3_set_decorators..__isub__..__isub__r)rZr+rrrr+sz!_set_decorators..__isub__csdd}||S)NcSsR||t|}}||||}}|D]}||q*|D]}||q>dSr)rr#rr%rotherZwantZhaverr%rrrrintersection_updates  zI_set_decorators..intersection_update..intersection_updater)rZr.rrrr. s z,_set_decorators..intersection_updatecsdd}||S)NcSs`t||stS||t|}}||||}}|D]}||q8|D]}||qL|Sr)r"r(rr#rr%r,rrr__iand__s   z3_set_decorators..__iand__..__iand__r)rZr/rrrr/s z!_set_decorators..__iand__csdd}||S)NcSsR||t|}}||||}}|D]}||q*|D]}||q>dSr)symmetric_differencer#rr%r,rrrsymmetric_difference_update+s  zY_set_decorators..symmetric_difference_update..symmetric_difference_updater)rZr1rrrr1*s z4_set_decorators..symmetric_difference_updatecsdd}||S)NcSs`t||stS||t|}}||||}}|D]}||q8|D]}||qL|Sr)r"r(r0r#rr%r,rrr__ixor__8s   z3_set_decorators..__ixor__..__ixor__r)rZr2rrrr27s z!_set_decorators..__ixor__rr)rr%r&rrrrr)r*r+r.r/r1r2rrrr_set_decoratorss&         r3c@seZdZdZdS)InstrumentedListz-An instrumented version of the built-in list.Nr/r0r1r2rrrrr4Msr4c@seZdZdZdS)InstrumentedSetz,An instrumented version of the built-in set.Nr5rrrrr6Qsr6c@seZdZdZdS)InstrumentedDictz-An instrumented version of the built-in dict.Nr5rrrrr7Usr7rBrr)rVr[r\r%r\r itervaluesc@sDeZdZdZddZejejd ddZej ejd ddZ dS) rIa)A basic dictionary-based collection class. Extends dict with the minimal bag semantics that collection classes require. ``set`` and ``remove`` are implemented in terms of a keying function: any callable that takes an object and returns an object for use as a dictionary key. cCs ||_dS)ahCreate a new collection with keying provided by keyfunc. keyfunc may be any callable that takes an object and returns an object for use as a dictionary key. The keyfunc will be called every time the ORM needs to add a member by value-only (such as when loading instances from the database) or remove a member. The usual cautions about dictionary keying apply- ``keyfunc(object)`` should return the same output for the life of the collection. Keying based on mutable properties can result in unreachable instances "lost" in the collection. NrJ)rrKrrrryszMappedCollection.__init__NcCs||}||||dS)z9Add an item by value, consulting the keyfunc for the key.N)rKrrr,rr-rrrr#s zMappedCollection.setcCs>||}|||kr.td||||f|||dS)zsb        #)  s (#+ >   %k&   9