U kf@sddZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm Z dd lm Z dd lm Z dd lm Z dd lmZdd lmZddlmZddlmZddlZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddl$m%Z%dd l&m'Z'dd!l(m)Z)dd"l*m+Z+dd#l,m-Z-dd$l.m/Z/dd%l0m1Z1dd&lm2Z2dd'l3m4Z4dd(l3m5Z5ed)Z6ed*Z7Gd+d,d,Z8Gd-d.d.e8Z9Gd/d0d0e8Z:d1d2d3d4Z;e;Gd5d6d6e9ee6e7fZdS);a3Provide support for tracking of in-place changes to scalar values, which are propagated into ORM change events on owning parent objects. .. _mutable_scalars: Establishing Mutability on Scalar Column Values =============================================== A typical example of a "mutable" structure is a Python dictionary. Following the example introduced in :ref:`types_toplevel`, we begin with a custom type that marshals Python dictionaries into JSON strings before being persisted:: from sqlalchemy.types import TypeDecorator, VARCHAR import json class JSONEncodedDict(TypeDecorator): "Represents an immutable structure as a json-encoded string." impl = VARCHAR def process_bind_param(self, value, dialect): if value is not None: value = json.dumps(value) return value def process_result_value(self, value, dialect): if value is not None: value = json.loads(value) return value The usage of ``json`` is only for the purposes of example. The :mod:`sqlalchemy.ext.mutable` extension can be used with any type whose target Python type may be mutable, including :class:`.PickleType`, :class:`_postgresql.ARRAY`, etc. When using the :mod:`sqlalchemy.ext.mutable` extension, the value itself tracks all parents which reference it. Below, we illustrate a simple version of the :class:`.MutableDict` dictionary object, which applies the :class:`.Mutable` mixin to a plain Python dictionary:: from sqlalchemy.ext.mutable import Mutable class MutableDict(Mutable, dict): @classmethod def coerce(cls, key, value): "Convert plain dictionaries to MutableDict." if not isinstance(value, MutableDict): if isinstance(value, dict): return MutableDict(value) # this call will raise ValueError return Mutable.coerce(key, value) else: return value def __setitem__(self, key, value): "Detect dictionary set events and emit change events." dict.__setitem__(self, key, value) self.changed() def __delitem__(self, key): "Detect dictionary del events and emit change events." dict.__delitem__(self, key) self.changed() The above dictionary class takes the approach of subclassing the Python built-in ``dict`` to produce a dict subclass which routes all mutation events through ``__setitem__``. There are variants on this approach, such as subclassing ``UserDict.UserDict`` or ``collections.MutableMapping``; the part that's important to this example is that the :meth:`.Mutable.changed` method is called whenever an in-place change to the datastructure takes place. We also redefine the :meth:`.Mutable.coerce` method which will be used to convert any values that are not instances of ``MutableDict``, such as the plain dictionaries returned by the ``json`` module, into the appropriate type. Defining this method is optional; we could just as well created our ``JSONEncodedDict`` such that it always returns an instance of ``MutableDict``, and additionally ensured that all calling code uses ``MutableDict`` explicitly. When :meth:`.Mutable.coerce` is not overridden, any values applied to a parent object which are not instances of the mutable type will raise a ``ValueError``. Our new ``MutableDict`` type offers a class method :meth:`~.Mutable.as_mutable` which we can use within column metadata to associate with types. This method grabs the given type object or class and associates a listener that will detect all future mappings of this type, applying event listening instrumentation to the mapped attribute. Such as, with classical table metadata:: from sqlalchemy import Table, Column, Integer my_data = Table('my_data', metadata, Column('id', Integer, primary_key=True), Column('data', MutableDict.as_mutable(JSONEncodedDict)) ) Above, :meth:`~.Mutable.as_mutable` returns an instance of ``JSONEncodedDict`` (if the type object was not an instance already), which will intercept any attributes which are mapped against this type. Below we establish a simple mapping against the ``my_data`` table:: from sqlalchemy.orm import DeclarativeBase from sqlalchemy.orm import Mapped from sqlalchemy.orm import mapped_column class Base(DeclarativeBase): pass class MyDataClass(Base): __tablename__ = 'my_data' id: Mapped[int] = mapped_column(primary_key=True) data: Mapped[dict[str, str]] = mapped_column(MutableDict.as_mutable(JSONEncodedDict)) The ``MyDataClass.data`` member will now be notified of in place changes to its value. Any in-place changes to the ``MyDataClass.data`` member will flag the attribute as "dirty" on the parent object:: >>> from sqlalchemy.orm import Session >>> sess = Session(some_engine) >>> m1 = MyDataClass(data={'value1':'foo'}) >>> sess.add(m1) >>> sess.commit() >>> m1.data['value1'] = 'bar' >>> assert m1 in sess.dirty True The ``MutableDict`` can be associated with all future instances of ``JSONEncodedDict`` in one step, using :meth:`~.Mutable.associate_with`. This is similar to :meth:`~.Mutable.as_mutable` except it will intercept all occurrences of ``MutableDict`` in all mappings unconditionally, without the need to declare it individually:: from sqlalchemy.orm import DeclarativeBase from sqlalchemy.orm import Mapped from sqlalchemy.orm import mapped_column MutableDict.associate_with(JSONEncodedDict) class Base(DeclarativeBase): pass class MyDataClass(Base): __tablename__ = 'my_data' id: Mapped[int] = mapped_column(primary_key=True) data: Mapped[dict[str, str]] = mapped_column(JSONEncodedDict) Supporting Pickling -------------------- The key to the :mod:`sqlalchemy.ext.mutable` extension relies upon the placement of a ``weakref.WeakKeyDictionary`` upon the value object, which stores a mapping of parent mapped objects keyed to the attribute name under which they are associated with this value. ``WeakKeyDictionary`` objects are not picklable, due to the fact that they contain weakrefs and function callbacks. In our case, this is a good thing, since if this dictionary were picklable, it could lead to an excessively large pickle size for our value objects that are pickled by themselves outside of the context of the parent. The developer responsibility here is only to provide a ``__getstate__`` method that excludes the :meth:`~MutableBase._parents` collection from the pickle stream:: class MyMutableType(Mutable): def __getstate__(self): d = self.__dict__.copy() d.pop('_parents', None) return d With our dictionary example, we need to return the contents of the dict itself (and also restore them on __setstate__):: class MutableDict(Mutable, dict): # .... def __getstate__(self): return dict(self) def __setstate__(self, state): self.update(state) In the case that our mutable value object is pickled as it is attached to one or more parent objects that are also part of the pickle, the :class:`.Mutable` mixin will re-establish the :attr:`.Mutable._parents` collection on each value object as the owning parents themselves are unpickled. Receiving Events ---------------- The :meth:`.AttributeEvents.modified` event handler may be used to receive an event when a mutable scalar emits a change event. This event handler is called when the :func:`.attributes.flag_modified` function is called from within the mutable extension:: from sqlalchemy.orm import DeclarativeBase from sqlalchemy.orm import Mapped from sqlalchemy.orm import mapped_column from sqlalchemy import event class Base(DeclarativeBase): pass class MyDataClass(Base): __tablename__ = 'my_data' id: Mapped[int] = mapped_column(primary_key=True) data: Mapped[dict[str, str]] = mapped_column(MutableDict.as_mutable(JSONEncodedDict)) @event.listens_for(MyDataClass.data, "modified") def modified_json(instance, initiator): print("json value modified:", instance.data) .. _mutable_composites: Establishing Mutability on Composites ===================================== Composites are a special ORM feature which allow a single scalar attribute to be assigned an object value which represents information "composed" from one or more columns from the underlying mapped table. The usual example is that of a geometric "point", and is introduced in :ref:`mapper_composite`. As is the case with :class:`.Mutable`, the user-defined composite class subclasses :class:`.MutableComposite` as a mixin, and detects and delivers change events to its parents via the :meth:`.MutableComposite.changed` method. In the case of a composite class, the detection is usually via the usage of the special Python method ``__setattr__()``. In the example below, we expand upon the ``Point`` class introduced in :ref:`mapper_composite` to include :class:`.MutableComposite` in its bases and to route attribute set events via ``__setattr__`` to the :meth:`.MutableComposite.changed` method:: import dataclasses from sqlalchemy.ext.mutable import MutableComposite @dataclasses.dataclass class Point(MutableComposite): x: int y: int def __setattr__(self, key, value): "Intercept set events" # set the attribute object.__setattr__(self, key, value) # alert all parents to the change self.changed() The :class:`.MutableComposite` class makes use of class mapping events to automatically establish listeners for any usage of :func:`_orm.composite` that specifies our ``Point`` type. Below, when ``Point`` is mapped to the ``Vertex`` class, listeners are established which will route change events from ``Point`` objects to each of the ``Vertex.start`` and ``Vertex.end`` attributes:: from sqlalchemy.orm import DeclarativeBase, Mapped from sqlalchemy.orm import composite, mapped_column class Base(DeclarativeBase): pass class Vertex(Base): __tablename__ = "vertices" id: Mapped[int] = mapped_column(primary_key=True) start: Mapped[Point] = composite(mapped_column("x1"), mapped_column("y1")) end: Mapped[Point] = composite(mapped_column("x2"), mapped_column("y2")) def __repr__(self): return f"Vertex(start={self.start}, end={self.end})" Any in-place changes to the ``Vertex.start`` or ``Vertex.end`` members will flag the attribute as "dirty" on the parent object: .. sourcecode:: python+sql >>> from sqlalchemy.orm import Session >>> sess = Session(engine) >>> v1 = Vertex(start=Point(3, 4), end=Point(12, 15)) >>> sess.add(v1) {sql}>>> sess.flush() BEGIN (implicit) INSERT INTO vertices (x1, y1, x2, y2) VALUES (?, ?, ?, ?) [...] (3, 4, 12, 15) {stop}>>> v1.end.x = 8 >>> assert v1 in sess.dirty True {sql}>>> sess.commit() UPDATE vertices SET x2=? WHERE vertices.id = ? [...] (8, 1) COMMIT Coercing Mutable Composites --------------------------- The :meth:`.MutableBase.coerce` method is also supported on composite types. In the case of :class:`.MutableComposite`, the :meth:`.MutableBase.coerce` method is only called for attribute set operations, not load operations. Overriding the :meth:`.MutableBase.coerce` method is essentially equivalent to using a :func:`.validates` validation routine for all attributes which make use of the custom composite type:: @dataclasses.dataclass class Point(MutableComposite): # other Point methods # ... def coerce(cls, key, value): if isinstance(value, tuple): value = Point(*value) elif not isinstance(value, Point): raise ValueError("tuple or Point expected") return value Supporting Pickling -------------------- As is the case with :class:`.Mutable`, the :class:`.MutableComposite` helper class uses a ``weakref.WeakKeyDictionary`` available via the :meth:`MutableBase._parents` attribute which isn't picklable. If we need to pickle instances of ``Point`` or its owning class ``Vertex``, we at least need to define a ``__getstate__`` that doesn't include the ``_parents`` dictionary. Below we define both a ``__getstate__`` and a ``__setstate__`` that package up the minimal form of our ``Point`` class:: @dataclasses.dataclass class Point(MutableComposite): # ... def __getstate__(self): return self.x, self.y def __setstate__(self, state): self.x, self.y = state As with :class:`.Mutable`, the :class:`.MutableComposite` augments the pickling process of the parent's object-relational state so that the :meth:`MutableBase._parents` collection is restored to all ``Point`` objects. ) annotations) defaultdict) AbstractSet)Any)Dict)Iterable)List)Optional)overload)Set)Tuple) TYPE_CHECKING)TypeVar)UnionN)WeakKeyDictionary)event)inspect)types)util)Mapper)_ExternalEntityType)_O)_T)AttributeEventToken) flag_modified)InstrumentedAttribute)QueryableAttribute) QueryContext)DeclarativeAttributeIntercept) InstanceState)UOWTransaction)SchemaEventTarget)Column) TypeEngine)memoized_property) SupportsIndex) TypeGuard_KT_VTc@sdeZdZdZeddddZedddd d d Zed d dddZed ddddddZ dS) MutableBasezPCommon base class to :class:`.Mutable` and :class:`.MutableComposite`. zWeakKeyDictionary[Any, Any]returncCstS)aDictionary of parent object's :class:`.InstanceState`->attribute name on the parent. This attribute is a so-called "memoized" property. It initializes itself with a new ``weakref.WeakKeyDictionary`` the first time it is accessed, returning the same object upon subsequent access. .. versionchanged:: 1.4 the :class:`.InstanceState` is now used as the key in the weak dictionary rather than the instance itself. )weakrefrselfr0F/opt/hc_python/lib64/python3.8/site-packages/sqlalchemy/ext/mutable.py_parentsszMutableBase._parentsstrrz Optional[Any]keyvaluer,cCs(|dkr dSd}t||t|fdS)aGiven a value, coerce it into the target type. Can be overridden by custom subclasses to coerce incoming data into a particular type. By default, raises ``ValueError``. This method is called in different scenarios depending on if the parent class is of type :class:`.Mutable` or of type :class:`.MutableComposite`. In the case of the former, it is called for both attribute-set operations as well as during ORM loading operations. For the latter, it is only called during attribute-set operations; the mechanics of the :func:`.composite` construct handle coercion during load operations. :param key: string name of the ORM-mapped attribute being set. :param value: the incoming value. :return: the method should return the coerced value, or raise ``ValueError`` if the coercion cannot be completed. Nz1Attribute '%s' does not accept objects of type %s) ValueErrortype)clsr5r6msgr0r0r1coerceszMutableBase.coercezQueryableAttribute[Any]Set[str] attributer,cCs|jhS)aGiven a descriptor attribute, return a ``set()`` of the attribute keys which indicate a change in the state of this attribute. This is normally just ``set([attribute.key])``, but can be overridden to provide for additional keys. E.g. a :class:`.MutableComposite` augments this set with the attribute keys associated with the columns that comprise the composite value. This collection is consulted in the case of intercepting the :meth:`.InstanceEvents.refresh` and :meth:`.InstanceEvents.refresh_flush` events, which pass along a list of attribute names that have been refreshed; the list is compared against this set to determine if action needs to be taken. r5r9r>r0r0r1_get_listen_keysszMutableBase._get_listen_keysboolz_ExternalEntityType[Any]None)r>r; parent_clsr,cs2|j||jk rdS|j}|ddddfdd ddd dd fd d }dd d dd dfdd }ddddfdd }ddddfdd }tj|ddddtj|ddddtj|d|dddtj|d|dddtj|d|ddddtj|d |dddtj|d!|ddddS)"]Establish this type as a mutation listener for the given mapped descriptor. NzInstanceState[_O]rrC)stateargsr,cs>|jd}|dk r:r0|}||j<|j|<dS)zListen for objects loaded or refreshed. Wrap the target data member's value with ``Mutable``. N)dictgetr;r2)rFrGval)r9r;r5r0r1loads   z.MutableBase._listen_on_attribute..loadz+Union[object, QueryContext, UOWTransaction] Iterable[Any])rFctxattrsr,cs|r|r|dSN) intersection)rFrMrN) listen_keysrKr0r1 load_attrssz4MutableBase._listen_on_attribute..load_attrszMutableBase | Noner)targetr6oldvalue initiatorr,csT||kr |St|s"|}|dk r4|j|<t|rP|jt|d|S)zListen for set/replace events on the target data member. Establish a weak reference to the parent object on the incoming value, remove it for the one outgoing. N) isinstancer;r2popr)rSr6rTrU)r9r5r0r1set_s    z.MutableBase._listen_on_attribute..set_zDict[str, Any])rF state_dictr,cs@|jd}|dk r.picklecsPd|krL|d}t|tr0|D]}|j|<qn|dD]}|j|<q.unpickleZ_sa_event_merge_wo_loadT)raw propagaterKrefreshZ refresh_flushset)r_retvalr`r]r^)r5class_rArlisten)r9r>r;rDrRrXr]r^r0)r9r;r5rQrKr1_listen_on_attributes`     z MutableBase._listen_on_attributeN) __name__ __module__ __qualname____doc__r%r2 classmethodr;rArfr0r0r0r1r*sr*c@sZeZdZdZddddZeddddd Zed dd d d Zeddd ddZdS)MutablezMixin that defines transparent propagation of change events to a parent object. See the example in :ref:`mutable_scalars` for usage information. rCr+cCs&|jD]\}}t||q dSz@Subclasses should call this method whenever change events occur.N)r2itemsrobj)r/parentr5r0r0r1changedUszMutable.changedzInstrumentedAttribute[_O]r=cCs||d|jdS)rETN)rfrdr@r0r0r1associate_with_attribute[sz Mutable.associate_with_attributer8)sqltyper,cs*ddddfdd }ttd|dS) aAssociate this wrapper with all future mapped columns of the given type. This is a convenience method that calls ``associate_with_attribute`` automatically. .. warning:: The listeners established by this method are *global* to all mappers, and are *not* garbage collected. Only use :meth:`.associate_with` for types that are permanent to an application, not with ad-hoc types else this will cause unbounded growth in memory usage. z Mapper[_O]r8rCmapperrdr,cs>|jr dS|jD](}t|jdjrt||jqdS)Nr) non_primary column_attrsrVcolumnsr8rrgetattrr5rurdpropr9rsr0r1listen_for_typews  z/Mutable.associate_with..listen_for_typemapper_configuredN)rrer)r9rsr}r0r|r1associate_witheszMutable.associate_withzTypeEngine[_T]cshtttr8tddddddd}dnd d d dd fd d }ttd|S)aAssociate a SQL type with this mutable Python type. This establishes listeners that will detect ORM mappings against the given type, adding mutation event trackers to those mappings. The type is returned, unconditionally as an instance, so that :meth:`.as_mutable` can be used inline:: Table('mytable', metadata, Column('id', Integer, primary_key=True), Column('data', MyMutableType.as_mutable(PickleType)) ) Note that the returned type is always an instance, even if a class is given, and that only columns which are declared specifically with that type instance receive additional instrumentation. To associate a particular mutable type with all occurrences of a particular type, use the :meth:`.Mutable.associate_with` classmethod of the particular :class:`.Mutable` subclass to establish a global association. .. warning:: The listeners established by this method are *global* to all mappers, and are *not* garbage collected. Only use :meth:`.as_mutable` for types that are permanent to an application, not with ad-hoc types else this will cause unbounded growth in memory usage. Zbefore_parent_attachzTypeEngine[Any]z Column[_T]rC)sqltyprpr,cSs||jd<dS)N_ext_mutable_orig_type)info)rrpr0r0r1_add_column_memosz,Mutable.as_mutable.._add_column_memoTF Mapper[_T]z*Union[DeclarativeAttributeIntercept, type]rtcsz|jr dSd}|jD]`}t|jtrr:|jjdksF|jjkr|jj|dsd|jj|<t ||j qdS)NZ_ext_mutable_listener_appliedrFT) rvrwrV expressionr#rrIr8rrryr5)rurdZ _APPLIED_KEYr{r9Zschema_event_checkrsr0r1r}s&    z+Mutable.as_mutable..listen_for_typer~)rZ to_instancerVr"rZ listens_forrer)r9rsrr}r0rr1 as_mutables!   zMutable.as_mutableN) rgrhrirjrqrkrrrrr0r0r0r1rlMs rlc@s2eZdZdZedddddZddd d Zd S) MutableCompositezMixin that defines transparent propagation of change events on a SQLAlchemy "composite" object to its owning parent or parents. See the example in :ref:`mutable_composites` for usage information. zQueryableAttribute[_O]r<r=cCs|jh|jjSrO)r5unionproperty_attribute_keysr@r0r0r1rAsz!MutableComposite._get_listen_keysrCr+cCsP|jD]@\}}|j|}t|||jD]\}}t|||q0q dSrm) r2rnruZ get_propertyzipZ_composite_values_from_instancersetattrro)r/rpr5r{r6 attr_namer0r0r1rqs  zMutableComposite.changedN)rgrhrirjrkrArqr0r0r0r1rsrrCr+cCs2dddddd}ttd|s.ttd|dS)Nrr8rCrtcSsJ|jD]>}t|drt|jtrt|jtr|jt||j d|qdS)Ncomposite_classF) Ziterate_propertieshasattrrVrr8 issubclassrrfryr5rzr0r0r1_listen_for_types    z3_setup_composite_listener.._listen_for_typer~)rcontainsrre)rr0r0r1_setup_composite_listeners rcsReZdZdZddddfdd Zerled3d ddd d d d Zedddddd Zd4dddddd Zn fdd Zdddfdd Zddddfdd Z eredddddZ eddddddZ d5ddddd dZ n fd!dZ d"d#fd$d% Z dd#fd&d' Z e d(dd)dd*d+Zd,d#d-d.Zd/dd0d1d2ZZS)6 MutableDictajA dictionary type that implements :class:`.Mutable`. The :class:`.MutableDict` object implements a dictionary that will emit change events to the underlying mapping when the contents of the dictionary are altered, including when values are added or removed. Note that :class:`.MutableDict` does **not** apply mutable tracking to the *values themselves* inside the dictionary. Therefore it is not a sufficient solution for the use case of tracking deep changes to a *recursive* dictionary structure, such as a JSON structure. To support this use case, build a subclass of :class:`.MutableDict` that provides appropriate coercion to the values placed in the dictionary so that they too are "mutable", and emit events up to their parent structure. .. seealso:: :class:`.MutableList` :class:`.MutableSet` r(r)rCr4cst|||dS)z4Detect dictionary set events and emit change events.N)super __setitem__rqr/r5r6 __class__r0r1rszMutableDict.__setitem__NzMutableDict[_KT, Optional[_T]]z Optional[_T])r/r5r6r,cCsdSrOr0rr0r0r1 setdefault szMutableDict.setdefaultcCsdSrOr0rr0r0r1r%sobjectcCsdSrOr0rr0r0r1r(cstj|}||SrO)rrrqr/argresultrr0r1r,s )r5r,cst||dS)z4Detect dictionary del events and emit change events.Nr __delitem__rq)r/r5rr0r1r1s zMutableDict.__delitem__r)akwr,cstj|||dSrOrupdaterq)r/rrrr0r1r6szMutableDict.update)_MutableDict__keyr,cCsdSrOr0)r/rr0r0r1rW<szMutableDict.popz_VT | _T)r_MutableDict__defaultr,cCsdSrOr0r/rrr0r0r1rW?sz_VT | _T | NonecCsdSrOr0rr0r0r1rWBscstj|}||SrOrrWrqrrr0r1rWHs zTuple[_KT, _VT]r+cst}||SrO)rpopitemrq)r/rrr0r1rMs zMutableDict.popitemcst|dSrOrclearrqr.rr0r1rRs zMutableDict.clearr3zMutableDict[_KT, _VT] | NonecCs0t||s(t|tr||St||S|SdS)z3Convert plain dictionary to instance of this class.N)rVrHrlr;r9r5r6r0r0r1r;Vs    zMutableDict.coercezDict[_KT, _VT]cCst|SrO)rHr.r0r0r1 __getstate__`szMutableDict.__getstate__z%Union[Dict[str, int], Dict[str, str]]rFr,cCs||dSrOrr/rFr0r0r1 __setstate__cszMutableDict.__setstate__)N)N)N)rgrhrirjrr r rrrrWrrrkr;rr __classcell__r0r0rr1rs4   rcsBeZdZdZdddddZddd d d Zd d dddZd ddddZdd ddfdd Zdddfdd Z dddfdd Z dddfd d! Z dddfd"d# Z dd$dd%d&Z dddd'fd(d) Zddd*fd+d, Zdd-fd.d/ Zd0dd1fd2d3 Zdd-fd4d5 Zed6d7d8d9d:d;ZZS)< MutableListaOA list type that implements :class:`.Mutable`. The :class:`.MutableList` object implements a list that will emit change events to the underlying mapping when the contents of the list are altered, including when values are added or removed. Note that :class:`.MutableList` does **not** apply mutable tracking to the *values themselves* inside the list. Therefore it is not a sufficient solution for the use case of tracking deep changes to a *recursive* mutable structure, such as a JSON structure. To support this use case, build a subclass of :class:`.MutableList` that provides appropriate coercion to the values placed in the dictionary so that they too are "mutable", and emit events up to their parent structure. .. seealso:: :class:`.MutableDict` :class:`.MutableSet` r&Tuple[type, Tuple[List[int]]]protor,cCs|jt|ffSrOrr[r/rr0r0r1 __reduce_ex__szMutableList.__reduce_ex__ Iterable[_T]rCrcCs||dd<dSrOr0rr0r0r1rszMutableList.__setstate__z_T | Iterable[_T]z TypeGuard[_T])r6r,cCs t| SrOrZis_non_string_iterabler/r6r0r0r1 is_scalarszMutableList.is_scalarzTypeGuard[Iterable[_T]]cCs t|SrOrrr0r0r1 is_iterableszMutableList.is_iterablezSupportsIndex | sliceindexr6r,csRt|tr$||r$t||n"t|trF||rFt|||dS)z.Detect list set events and emit change events.N)rVr&rrrslicerrq)r/rr6rr0r1rs zMutableList.__setitem__)rr,cst||dS)z.Detect list del events and emit change events.Nr)r/rrr0r1rs zMutableList.__delitem__rrr,cstj|}||SrOrrrr0r1rWs zMutableList.pop)xr,cst||dSrO)rr\rqr/rrr0r1r\s zMutableList.appendcst||dSrO)rextendrqrrr0r1rs zMutableList.extendzMutableList[_T]cCs|||SrO)rrr0r0r1__iadd__s zMutableList.__iadd__)irr,cst|||dSrO)rinsertrq)r/rrrr0r1rszMutableList.insert)rr,cst||dSrOrremoverq)r/rrr0r1rs zMutableList.remover+cst|dSrOrr.rr0r1rs zMutableList.clearr)rr,c stjf||dSrO)rsortrq)r/rrr0r1rszMutableList.sortcst|dSrO)rreverserqr.rr0r1rs zMutableList.reverser3zMutableList[_T] | _TzOptional[MutableList[_T]]r4cCs0t||s(t|tr||St||S|SdS)z-Convert plain list to instance of this class.N)rVr[rlr;rr0r0r1r;s    zMutableList.coerce)rgrhrirjrrrrrrrWr\rrrrrrrrkr;rr0r0rr1ris$ rcsJeZdZdZdddfdd Zdddfdd Zdddfd d Zdddfd d ZdddddZdddddZ dddddZ dddddZ dddfdd Z dddfdd Z dddfd d! Zd"ddfd#d$ Zdd%fd&d' Zed(d"d)d*d+d,Zd-d%d.d/Zddd0d1d2Zd3d4d5d6d7ZZS)8 MutableSeta0A set type that implements :class:`.Mutable`. The :class:`.MutableSet` object implements a set that will emit change events to the underlying mapping when the contents of the set are altered, including when values are added or removed. Note that :class:`.MutableSet` does **not** apply mutable tracking to the *values themselves* inside the set. Therefore it is not a sufficient solution for the use case of tracking deep changes to a *recursive* mutable structure. To support this use case, build a subclass of :class:`.MutableSet` that provides appropriate coercion to the values placed in the dictionary so that they too are "mutable", and emit events up to their parent structure. .. seealso:: :class:`.MutableDict` :class:`.MutableList` rrCrcstj||dSrOrr/rrr0r1rs zMutableSet.updaterLcstj||dSrO)rintersection_updaterqrrr0r1rs zMutableSet.intersection_updatecstj||dSrO)rdifference_updaterqrrr0r1rs zMutableSet.difference_updatecstj||dSrO)rsymmetric_difference_updaterqrrr0r1rs z&MutableSet.symmetric_difference_updatezAbstractSet[_T]zMutableSet[_T])otherr,cCs|||SrOrr/rr0r0r1__ior__s zMutableSet.__ior__zAbstractSet[object]cCs|||SrO)rrr0r0r1__iand__s zMutableSet.__iand__cCs|||SrO)rrr0r0r1__ixor__s zMutableSet.__ixor__cCs|||SrO)rrr0r0r1__isub__s zMutableSet.__isub__r)elemr,cst||dSrO)raddrqr/rrr0r1r s zMutableSet.addcst||dSrOrrrr0r1r s zMutableSet.removecst||dSrO)rdiscardrqrrr0r1rs zMutableSet.discardrcstj|}||SrOrrrr0r1rWs zMutableSet.popr+cst|dSrOrr.rr0r1rs zMutableSet.clearr3zOptional[MutableSet[_T]]rcCs0t||s(t|tr||St||S|SdS)z,Convert plain set to instance of this class.N)rVrbrlr;)r9rr6r0r0r1r;s    zMutableSet.coercezSet[_T]cCst|SrO)rbr.r0r0r1r(szMutableSet.__getstate__rcCs||dSrOrrr0r0r1r+szMutableSet.__setstate__r&rrcCs|jt|ffSrOrrr0r0r1r.szMutableSet.__reduce_ex__)rgrhrirjrrrrrrrrrrrrWrrkr;rrrrr0r0rr1rs& r)?rj __future__r collectionsrtypingrrrrrr r r r r rrr-rrrrrZormrZ orm._typingrrrZorm.attributesrrrrZ orm.contextrZ orm.decl_apirZ orm.stater Zorm.unitofworkr!Zsql.baser"Z sql.schemar#Z sql.type_apir$r%Z util.typingr&r'r(r)r*rlrrrrrr0r0r0r1shb                                     9 hh