o znh@s4dZddlZddlZddlmZddlmZddlmZddlm Z dd l m Z gd Z e j ZGd d d eZGd ddeZGdddeZddZGdddeZddZddZGdddeZedZ GdddeZdPddZd d!Zd"d#Zd$d%Zd&d'Z d(d)Z!d*d+Z"d,d-Z#d.d/Z$dPd0d1Z%dPd2d3Z&dPd4d5Z'd6d7Z(d8d9Z)e*e+fZ,d:d;Z-dd?Z/Gd@dAdAe0Z1GdBdCdCe*Z2GdDdEdEe3Z4e0e1e*e2e3e4iZ5e0dFdGdHdIe(fe*dJdGdHdIe/fe3e j6rdKdLie)fndKdMie)fiZ7GdNdOdOe3Z8ee8ee1ee2dS)QaNSupport 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) expression) 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. cC||_t|dk|_dSNr)colslen composite)selfrrE/usr/local/lib/python3.10/dist-packages/sqlalchemy/orm/collections.py__init__z_PlainColumnGetter.__init__cCs t|jSN)_SerializableColumnGetterV2_reduce_from_colsrrrrr __reduce__ z_PlainColumnGetter.__reduce__cCs|jSr)r)rmapperrrr_colssz_PlainColumnGetter._colscsDt|tfdd|D}|jrt|S|dS)Ncsg|] }j|qSr)_get_state_attr_by_columndict).0colmstaterr sz/_PlainColumnGetter.__call__..r)rinstance_state _state_mapperr rtuplervaluekeyrr%r__call__s   z_PlainColumnGetter.__call__N)__name__ __module__ __qualname____doc__rrr r/rrrrrs   rc@s(eZdZdZddZddZddZdS) _SerializableColumnGetterzlColumn-based getter used in version 0.7.6 only. Remains here for pickle compatibility with 0.7.6. cCrrcolkeysrrrr6rrrrrz"_SerializableColumnGetter.__init__cC t|jffSr)r4r6rrrrrrz$_SerializableColumnGetter.__reduce__cs@t|tfdd|jD}|jrt|S|dS)Ncs$g|]}jjj|qSr)r!r" mapped_tablecolumns)r#kr%rrr(s z6_SerializableColumnGetter.__call__..r)rr)r*r6rr+r,rr%rr/s   z"_SerializableColumnGetter.__call__N)r0r1r2r3rrr/rrrrr4s  r4c@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. cCrrr5r7rrrrrz$_SerializableColumnGetterV2.__init__cCs|j|jffSr) __class__r6rrrrrz&_SerializableColumnGetterV2.__reduce__cs$ddfdd|D}t|ffS)NcSst|jtjs dS|jjSr) isinstancetabler TableClauser.)crrr _table_keyszA_SerializableColumnGetterV2._reduce_from_cols.._table_keycsg|] }|j|fqSr)r.)r#rArBrrr(szA_SerializableColumnGetterV2._reduce_from_cols..)r)clsrr6rrCrrs z-_SerializableColumnGetterV2._reduce_from_colscCshg}t|jdd}|jD]%\}}|dus|dus||vr&||jj|q ||j|j|q |S)Nmetadata)getattr local_tabler6appendrAtables)rrrrEckeytkeyrrrr sz!_SerializableColumnGetterV2._colsN) r0r1r2r3rr classmethodrr rrrrrs   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|]}t|dqS) mapping_spec)r_only_column_elements)r#qrrrr(s z,column_mapped_collection..ctSrMappedCollectionrkeyfuncrrz*column_mapped_collection..)rto_listr)rMrrrSrr s   r c@s$eZdZddZddZddZdS)_SerializableAttrGettercCs||_t||_dSr)nameoperator attrgettergetter)rrYrrrrsz _SerializableAttrGetter.__init__cCs ||Srr\)rtargetrrrr/ z _SerializableAttrGetter.__call__cCr8r)rXrYrrrrrrz"_SerializableAttrGetter.__reduce__N)r0r1r2rr/rrrrrrXs rXcst|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. 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. crPrrQrr]rrrUrVz-attribute_mapped_collection..)rX) attr_namerr]rr s r cs 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. crPrrQrrSrrrU'rVz#mapped_collection..rrSrrSrr s r c@seZdZdZeddZeddZeddZedd Zee d d d d Z e Z ee ddddZ eddZeddZeddZeddZdS)r a}Decorators for entity collection classes. The decorators fall into two groups: annotations and interception recipes. The annotating decorators (appender, remover, iterator, linker, 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): ... cC 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_rolefnrrrrbDs)zcollection.appendercCra)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. removerrcrerrrrgpszcollection.removercCra)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): ... iteratorrcrerrrrhs zcollection.iteratorcCra)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_instrumentedrerrrinternally_instrumentedsz"collection.internally_instrumentedz1.0zThe :meth:`.collection.linker` handler is deprecated and will be removed in a future release. Please refer to the :meth:`.AttributeEvents.init_collection` and :meth:`.AttributeEvents.dispose_collection` event handlers. cCra)aTag the method as a "linked to attribute" event handler. This optional event handler will be called when the collection class is linked to or unlinked from the InstrumentedAttribute. It is invoked immediately after the '_sa_adapter' property is set on the instance. A single argument is passed: the collection adapter that has been linked, or None if unlinking. linkerrcrerrrrkszcollection.linkerz1.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.cCra)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. converterrcrerrrrls%zcollection.convertercfdd}|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): ... cdf|_|S)Nfire_append_event_sa_instrument_beforereargrr decorator z"collection.adds..decoratorrrsrtrrrradds zcollection.addscrm)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)Nrofire_remove_event)rq_sa_instrument_afterrerrrrrts z&collection.replaces..decoratorrrvrrrrreplaces s zcollection.replacescrm)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. crnNryrprerrrrrt3ruz%collection.removes..decoratorrrvrrrrremoves"rxzcollection.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. cSrar|)rzrerrrrtIsz,collection.removes_return..decoratorr)rtrrrremoves_return9szcollection.removes_returnN)r0r1r2r3 staticmethodrbrgrhrjr deprecatedrklinkrlrwr{r}r~rrrrr *s@ +        r _sa_adapterc@seZdZdZdZddZddZeddZed d Z d d Z d.ddZ ddZ ddZ ddZd.ddZddZd.ddZddZddZd d!Zd"d#ZeZd.d$d%Zd.d&d'Zd.d(d)Zd*d+Zd,d-Zd S)/CollectionAdapteraiBridges between the ORM and arbitrary Python collections. Proxies base-level collection operations (append, remove, iterate) to the underlying Python collection, and emits add/remove events for entities entering or leaving the collection. The ORM uses :class:`.CollectionAdapter` exclusively for interaction with entity collections. )attr_key_data owner_state _converter invalidatedcCs8||_|j|_t||_||_||_|j|_ d|_ dS)NF) rr.rweakrefrefrrr _sa_converterrr)rrrdatarrrrjs  zCollectionAdapter.__init__cCstddS)Nz%This collection has been invalidated.)rwarnrrrr_warn_invalidatedsr=z#CollectionAdapter._warn_invalidatedcCs|S)z$The entity collection being adapted.)rrrrrrvszCollectionAdapter.datacCs|jj|j|uS)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. )rr"rrrrrr_referenced_by_owner{sz&CollectionAdapter._referenced_by_ownercC |jSrr _sa_appenderrrrr bulk_appenderr_zCollectionAdapter.bulk_appenderNcC|j||ddS)z8Add an entity to the collection, firing mutation events. _sa_initiatorNrritem initiatorrrrappend_with_eventsz#CollectionAdapter.append_with_eventcC|j|dddSz=Add or restore an entity to the collection, firing no events.FrNrrrrrrappend_without_eventz&CollectionAdapter.append_without_eventcCs$|j}|D]}||ddqdSrr)ritemsrbrrrrappend_multiple_without_events z/CollectionAdapter.append_multiple_without_eventcCrrr _sa_removerrrrr bulk_removerr_zCollectionAdapter.bulk_removercCr)z=Remove an entity from the collection, firing mutation events.rNrrrrrremove_with_eventrz#CollectionAdapter.remove_with_eventcCr)z7Remove an entity from the collection, firing no events.FrNrrrrrremove_without_eventrz&CollectionAdapter.remove_without_eventcCs(|j}t|D]}|||dq dS)z>Empty the collection, firing a mutation event for each entity.rNrrlist)rrrgrrrrclear_with_event  z"CollectionAdapter.clear_with_eventcCs(|j}t|D]}||ddq dS)z'Empty the collection, firing no events.FrNr)rrgrrrrclear_without_eventrz%CollectionAdapter.clear_without_eventcCst|S)z(Iterate over entities in the collection.)iterr _sa_iteratorrrrr__iter__szCollectionAdapter.__iter__cCstt|S)z!Count entities in the collection.)rrrrrrrr__len__szCollectionAdapter.__len__cCsdSNTrrrrr__bool__szCollectionAdapter.__bool__cCs2|dur|jr ||j|j|jj||S|S)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. F)rrrrorr"rrrrros z#CollectionAdapter.fire_append_eventcCs6|dur|jr ||j|j|jj||dSdS)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)rrrryrr"rrrrrysz#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)rrrfire_pre_remove_eventrr")rrrrrrs   z'CollectionAdapter.fire_pre_remove_eventcCs|j|j|jj|j|jdS)N)r.r owner_clsrr)rrclass_rrrrrr __getstate__s zCollectionAdapter.__getstate__cCs\|d|_|d|_t|d|_|dj|_||d_|d|_t |d|jj |_ dS)Nr.rrrr) rrrrrrrrrrFimplr)rdrrr __setstate__s     zCollectionAdapter.__setstate__r)r0r1r2r3 __slots__rrpropertyrrrrrrrrrrrrrr __nonzero__roryrrrrrrrrTs6            rc Cst|tsJtj}||pd}||pd}||pd|}||}|} |p,dD]} | |vr:| | |dq-| |vrD| | ddq-|rS|D] } |j| |dqIdSdS)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>rr IdentitySet intersection differencerry) valuesexisting_adapter new_adapterridsetexisting_idset constants additionsremovalsrbmemberrrr bulk_replaces$    rcCs|tvrt|}t|}|tvrt||}|}tr?zt|ddt|kr3t|Wt|SWt|Stw|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. riN) __canned_instrumentationtype__converting_factory__instrumentation_mutexacquirerFid_instrument_classrelease)factoryrDrrrprepare_instrumentation's"     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 instrumented_clsoriginal_factoryrrwrapperRsz%__converting_factory..wrapperz %sWrapper)rr0r3) specimen_clsrrrrrrJs  rcCsH|jdkr tdt|\}}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)r1sa_exc ArgumentError_locate_roles_and_methods_setup_canned_roles_assert_required_roles_set_collection_attributesrDrolesmethodsrrrr]s    rc Csi}i}|jD]b}t|D]Y\}}t|sqt|dr-|j}|dvs'J|||d\}}t|drE|j\} } | dvsAJ| | f}t|drU|j } | dvsSJ| }|r_||f||<q|rhdd|f||<qq||fS)zgsearch for _sa_instrument_role-decorated methods in method resolution order, assign to roles. rd)rbrgrhrkrl)NNrq)roryrzN) __mro__varsrrcallablehasattrrd setdefaultrqrz) rDrrsuperclsrYmethodrolebeforeafteropargumentrrrrrs4          rc Cst|}|tvr@t|\}}|D] \}}|||q|D]\}} t||d} | r?||vr?t| ds?t||| | q"dSdS)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 Nri)rduck_type_collection __interfacesrrrFrsetattr) rDrrcollection_type canned_roles decoratorsrrYrrtrfrrrrs   rcCsd|vs t||dstd|j|d|vr)tt||dds)d||d<d|vs4t||dsType %s must elect an appender method to be a collection classri)rorNrgzType %s must elect an iterator method to be a collection classN)rrrr0rFrrrrrs6  rc Cs|D]\}\}}}t||tt|||||q|D]\}}t|d|t||qd|_t|ds9d|_t||_dS)zkapply ad-hoc instrumentation from decorators, class-level defaults and implicit role declarations z_sa_%sNr) rr_instrument_membership_mutatorrFrrrrri)rDrr method_namerrrrrrrrs rcsr0tttd}ttr!t|kr|pdn|vr+|nd~fdd}d|_t drGj |_ j |_ j |_ |S)zIRoute method args and/or return value through the collection adapter.rNcsr1dur|vrtd|}nt|kr!|}n|vr*|}ntd|dd}|dur>d}n|dj}rO|rOt|||rS|sZ|i|S|i|}|durmt||||S)NzMissing argument %srFr)rrrpoprrF)argskwr-rexecutorresrrrr named_argpos_argrrrs4      z/_instrument_membership_mutator..wrapperTrd) rrflatten_iteratorrr>intrindexrirrdr0r3)rrrrfn_argsrrrrrs&  # rcCs"|dur|j}|r|||}|S)z^Run set events. This event always occurs before the collection is actually mutated. F)rror rrrrrr__set,s  rcCs*|dur|j}|r|||dSdSdS)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)rryrrrr__del:s  rcCs|j}|r ||dSdS)z;An event which occurs on a before a pop() operation occurs.N)rr)r rrrrr __before_popIsrc sddfdd}fdd}fdd}fd d }fd d }tjr1fd d}fdd}fdd}fdd}fdd} tjsLfdd} t} | d| S)z:Tailored instrumentation wrappers for any list-like class.cSd|_tt|jj|_dSr)rirFrr0r3rerrr_tidySz_list_decorators.._tidycdfdd }||S)Ncst|||}||dSrr)rrrrerrrHXs z0_list_decorators..append..appendrr)rfrHr rerrHWsz _list_decorators..appendcr )Ncst|||||dSrrrr-rrerrremove`s z0_list_decorators..remove..removerrrfrr rerr_z _list_decorators..removecfdd}||S)Ncst||}|||dSrr )rrr-rerrinsertis z0_list_decorators..insert..insertr)rfrr rerrhs z _list_decorators..insertcr)Nc sNt|ts||}|durt||t||}|||dS|jp#d}|jp(d}|dkr3|t|7}|jdur<|j}nt|}|dkrJ|t|7}|dkry||urTdSt|||D] }t||kre||=qZt |D] \}}| |||qjdSt t|||} t|t| krt dt|t| ft | |D] \}}|||qdS)NrrzBattempt to assign sequence of size %s to extended slice of size %s)r>slicerrstepstartrstoprange enumeraterr ValueErrorzip __setitem__) rrr-existingrrrirrngrerrrqsF         z:_list_decorators..__setitem__..__setitem__rrfrr rerrps (z%_list_decorators..__setitem__cr)NcsPt|ts||}t||||dS||D]}t||q||dSr)r>rrrrrrerr __delitem__s    z:_list_decorators..__delitem__..__delitem__rrfr#r rerr#s  z%_list_decorators..__delitem__cr)Ncs@||D]}t|qfdd|D}|||dS)Ncsg|]}t|qSrr )r#r-rrrr(szP_list_decorators..__setslice__..__setslice__..r)rrendrr-rerr __setslice__s z<_list_decorators..__setslice__..__setslice__r)rfr&r rerr& z&_list_decorators..__setslice__cr)Ncs,|||D]}t||q|||dSrr)rrr%r-rerr __delslice__s z<_list_decorators..__delslice__..__delslice__r)rfr(r rerr( z&_list_decorators..__delslice__cdd}||S)NcS|D]}||qdSrrHriterabler-rrrextend z0_list_decorators..extend..extendr)rfr/r rrr/z _list_decorators..extendcr*)NcSs|D]}||q|Srr,r-rrr__iadd__s z4_list_decorators..__iadd__..__iadd__r)rfr2r rrr2z"_list_decorators..__iadd__cdfdd }||S)Ncs t|||}t|||Srrrr"rerrrs  z*_list_decorators..pop..popr5rrfrr rerrz_list_decorators..popcr4)Nr5cs |D]}t||q|dSrrr"rerrclears  z._list_decorators..clear..clearr7rrfr:r rerr:rz_list_decorators..clearr )rpy2klocalscopyr) rHrrrr#r&r(r/r2rr:lrr r_list_decoratorsPs"    ,      r@csddtdfdd}fdd}fdd }fd d }fd d }fdd}fdd}t}|d|d|S)zBTailored instrumentation wrappers for any dict-like mapping class.cSrr)rirFr"r0r3rerrrr r z_dict_decorators.._tidy Unspecifiedcr )Ncs4||vr t||||t|||}|||dSr)rr)rr.r-rrerrrs z:_dict_decorators..__setitem__..__setitem__rrr!r rerrr9z%_dict_decorators..__setitem__cr )Ncs&||vr t||||||dSrr)rr.rrerrr#sz:_dict_decorators..__delitem__..__delitem__rrr$r rerr#rz%_dict_decorators..__delitem__cr)Ncs$|D] }t|||q|dSrr)rr.rerrr:s z._dict_decorators..clear..clearrr;r rerr:r)z_dict_decorators..clearcsffdd }||S)NcsBt|||v}|ur||}n|||}|rt|||Srr6)rr.default_to_delr)rArfrrrs   z*_dict_decorators..pop..poprr8rAr rerrs z_dict_decorators..popcr)Ncs"t||}t||d|Srr6rrerrpopitem)sz2_dict_decorators..popitem..popitemr)rfrEr rerrE(r'z!_dict_decorators..popitemcsddd}||S)NcSs"||vr ||||S||Sr)r __getitem__)rr.rBrrrr3s  z8_dict_decorators..setdefault..setdefaultrr)rfrr rrr2s z$_dict_decorators..setdefaultcsffdd }||S)Ncs|ur8t|dr#t|D]}||vs||||ur!||||<q n|D]\}}||vs3|||ur7|||<q%|D]}||vsH||||urN||||<q:dS)Nkeys)rr)r__otherrr.r-)rArrupdate>s      z0_dict_decorators..update..updaterrfrIrDrrrI=sz _dict_decorators..updater rsymbolr=r>r)rr#r:rrErrIr?rrDr_dict_decoratorss        rMcCst|t|jfS)zKAllow only set, frozenset and self.__class__-derived objects in binops.)r>_set_binop_basesr<robjrrr_set_binops_check_strictXsrQcCs t|t|jfpt|tkS)z5Allow anything set-like to participate in set binops.)r>rNr<rrsetrOrrr_set_binops_check_loose^s rScsddtd}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.cSrr)rirFrRr0r3rerrrr ir z_set_decorators.._tidyrAcr )Ncs"||vr t|||}||dSrr rrerraddps z)_set_decorators..add..addrr)rfrTr rerrTor9z_set_decorators..addcr )Nc"||vr t|||||dSrrrrerrdiscardz z1_set_decorators..discard..discardrr)rfrVr rerrVyz _set_decorators..discardcr )NcrUrrrrerrrrWz/_set_decorators..remove..removerrrr rerrrXz_set_decorators..removecr)Ncst||}t|||Srr6rrerrrs z)_set_decorators..pop..poprr8r rerrs z_set_decorators..popcr*)NcSst|D]}||qdSr)rrrrrrr:s  z-_set_decorators..clear..clearrr;r rrr:r1z_set_decorators..clearcr*)NcSr+r)rTrr-rrrrrIr0z/_set_decorators..update..updaterrJr rrrIr1z_set_decorators..updatecr*)NcS&t||stS|D]}||q |Sr)rQNotImplementedrTrYrrr__ior__  z1_set_decorators..__ior__..__ior__r)rfr\r rrr\r3z _set_decorators..__ior__cr*)NcSr+r)rVrYrrrdifference_updater0zE_set_decorators..difference_update..difference_updater)rfr^r rrr^r1z*_set_decorators..difference_updatecr*)NcSrZr)rQr[rVrYrrr__isub__r]z3_set_decorators..__isub__..__isub__r)rfr_r rrr_r3z!_set_decorators..__isub__cr*)NcSR||t|}}||||}}|D]}||q|D]}||qdSr)rrRrrTrotherwanthaverrTrrrrintersection_update  zI_set_decorators..intersection_update..intersection_updater)rfrer rrre z,_set_decorators..intersection_updatecr*)NcS`t||stS||t|}}||||}}|D]}||q|D]}||q&|Sr)rQr[rrRrrTrarrr__iand__   z3_set_decorators..__iand__..__iand__r)rfrir rrri z!_set_decorators..__iand__cr*)NcSr`r)symmetric_differencerRrrTrarrrsymmetric_difference_updaterfzY_set_decorators..symmetric_difference_update..symmetric_difference_updater)rfrmr rrrmrgz4_set_decorators..symmetric_difference_updatecr*)NcSrhr)rQr[rlrRrrTrarrr__ixor__rjz3_set_decorators..__ixor__..__ixor__r)rfrnr rrrnrkz!_set_decorators..__ixor__r rK)rArTrVrrr:rIr\r^r_rerirmrnr?rr r_set_decoratorsfs&         roc@eZdZdZdS)InstrumentedListz-An instrumented version of the built-in list.Nr0r1r2r3rrrrrq rqc@rp)InstrumentedSetz,An instrumented version of the built-in set.Nrrrrrrrt rsrtc@rp)InstrumentedDictz-An instrumented version of the built-in dict.NrrrrrrrursrurHrr)rbrgrhrTrhr itervaluesc@sDeZdZdZddZejejd ddZej ejd ddZ dS) rRa)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. NrS)rrTrrrr5s zMappedCollection.__init__NcCs||}||||dS)z9Add an item by value, consulting the keyfunc for the key.N)rTrrr-rr.rrrrREs zMappedCollection.setcCs>||}|||krtd||||f|||dS)zsb      #)  ( ,(#,  >  %a$   9