L i,dZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm Z dd lm Z dd lm Z dd lm Z dd lmZdd lmZddlmZddlmZddlZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddl#m$Z$ddl%m&Z&dd l'm(Z(dd!l)m*Z*dd"l+m,Z,dd#l-m.Z.dd$l/m0Z0dd%l1m2Z2dd&l3m4Z4dd'l5m6Z6ed(Z7ed)Z8Gd*d+Z9Gd,d-e9Z:Gd.d/e9Z;d7d0Z<e<Gd1d2e:ee7e8fZ=Gd3d4e:e eZ>Gd5d6e:e eZ?y)8a3Provide 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)Mapper)_ExternalEntityType)_O)_T)AttributeEventToken) flag_modified)InstrumentedAttribute)QueryableAttribute) QueryContext)DeclarativeAttributeIntercept) InstanceState)UOWTransaction)_TypeEngineArgument)SchemaEventTarget)Column) TypeEngine)memoized_property) SupportsIndex_KT_VTcheZdZdZeddZeddZed dZe d dZ y) MutableBasezPCommon base class to :class:`.Mutable` and :class:`.MutableComposite`. c*tjS)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. )weakrefrselfs \/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sqlalchemy/ext/mutable.py_parentszMutableBase._parentss((**c>|yd}t||t|fz)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)clskeyvaluemsgs r0coercezMutableBase.coerces*0 =AT%[1122r2c|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. )r7r6 attributes r0_get_listen_keyszMutableBase._get_listen_keyss" r2cl |j||jury|j}j| dfd d fd } dfd } dfd } dfd }tj|d dd tj|d dd tj|d |dd tj|d |dd tj|d |dddtj|d|dd tj|d|dd y)]Establish this type as a mutation listener for the given mapped descriptor. Nc|jjd}|7r%j|}|J||j<|j|<yy)zListen for objects loaded or refreshed. Wrap the target data member's value with ``Mutable``. N)dictgetr:r1)stateargsvalr6r:r7s r0loadz.MutableBase._listen_on_attribute..loads[**..d+C**S#.C?*?&)EJJsO&) U# r2c>|rj|r |yyN) intersection)rDctxattrs listen_keysrGs r0 load_attrsz4MutableBase._listen_on_attribute..load_attrss! K44U;U .set_si  eS) 3. ),v&(C(!!%%gfot<Lr2c|jjd}|.d|vrtt|d<|dj |yyNzext.mutable.values)rBrCrlistappend)rD state_dictrFr7s r0picklez0MutableBase._listen_on_attribute..pickle2sT**..d+C'z97B47HJ34/05<.unpickle;sn$z1'(<= j$/)2.1 U+2 **>?D2.1 U+22r2_sa_event_merge_wo_loadT)raw propagaterGrefresh refresh_flushset)r`retvalrar[r^)rDInstanceState[_O]rErreturnNone)rDrfrKz+Union[object, QueryContext, UOWTransaction]rL Iterable[Any]rgrh) rRrfr8MutableBase | NonerSrjrTrrgrj)rDrfrZzDict[str, Any]rgrh)r7class_r>rlisten) r6r=r: parent_clsrNrUr[r^r7rMrGs ` ` @@@r0_listen_on_attributez MutableBase._listen_on_attributesmm Y-- - %% **95  * $ < !    % % ) +     2 B$ B2@ B  B 2$ 22@ 2  2   %     Z44H  :44      udTT   Z6ttL  H$$ r2N)rgzWeakKeyDictionary[Any, Any])r7strr8rrgz Optional[Any])r=QueryableAttribute[Any]rgSet[str])r=rpr:boolrmz_ExternalEntityType[Any]rgrh) __name__ __module__ __qualname____doc__r&r1 classmethodr:r>rnr2r0r+r+s ++ 338$n *n n - n  n n r2r+cVeZdZdZddZe ddZed dZed dZy) MutablezMixin that defines transparent propagation of change events to a parent object. See the example in :ref:`mutable_scalars` for usage information. c||jjD]\}}t|j|!yz@Subclasses should call this method whenever change events occur.N)r1itemsrobj)r/parentr7s r0changedzMutable.changedhs4 ==..0 -KFC &**, , -r2c>|j|d|jy)r@TN)rnrkr<s r0associate_with_attributez Mutable.associate_with_attributens   D)2B2BCr2cLdfd }tjtd|y)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. c|jry|jD]K}t|jdjs'j t ||jMy)Nr) non_primary column_attrsrPcolumnsr5rgetattrr7)mapperrkpropr6sqltypes r0listen_for_typez/Mutable.associate_with..listen_for_typesW!!++ Ldll1o22G<001JK Lr2mapper_configuredN)rz Mapper[_O]rkr5rgrh)rrlr)r6rrs`` r0associate_withzMutable.associate_withxs$ L  V0/Br2ctjttr&t j d dd}dnd dfd }t j td|S) a?Associate 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. before_parent_attachc"||jd<y)N_ext_mutable_orig_type)info)sqltyprs r0_add_column_memoz,Mutable.as_mutable.._add_column_memos 9? 45r2TFc|jryd}|jD]}t|jtsr'|jj j dus|jjus`|jj j |drd|jj |<jt||jy)N_ext_mutable_listener_appliedrFT) rrrP expressionr$rrCr5rrr7)rrk _APPLIED_KEYrr6schema_event_checkrs r0rz+Mutable.as_mutable..listen_for_types!!:L++ P t7/ $ 4 4 8 8 8! '!'  ??//7: ??//33L%H=A,,\:44WVTXX5NO' Pr2r)rzTypeEngine[Any]rz Column[_T]rgrh)r Mapper[_T]rkz*Union[DeclarativeAttributeIntercept, type]rgrh)r to_instancerPr#r listens_forrlr)r6rrrrs`` @r0 as_mutablezMutable.as_mutablesF##G, g0 1   w(> ? ?' ?" ? ?@ ? "& !&  P P> P P:  V0/Br2Nrgrh)r=zInstrumentedAttribute[_O]rgrh)rr5rgrh)rz_TypeEngineArgument[_T]rgzTypeEngine[_T]) rsrtrurvrrwrrrrxr2r0rzrz`s`- D1D DDCC4SSr2rzc*eZdZdZeddZddZy)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. cb|jhj|jjSrI)r7unionproperty_attribute_keysr<s r0r>z!MutableComposite._get_listen_keyss% $$Y%7%7%G%GHHr2c|jjD]h\}}|jj|}t |j ||j D] \}}t|j||"jyr|) r1r}r get_propertyzip_composite_values_from_instancersetattrr~)r/rr7rr8 attr_names r0rzMutableComposite.changeds| ==..0 8KFC==--c2D$'44T:$$% 8 y i7  8 8r2N)r=zQueryableAttribute[_O]rgrqr)rsrtrurvrwr>rrxr2r0rrs"II 8r2rczdd}tjtd|stjtd|yy)Nc|jD]v}t|dst|jts+t |jt sF|jjt||jd|xy)Ncomposite_classF) iterate_propertieshasattrrPrr5 issubclassrrnrr7)rrkrs r0_listen_for_typez3_setup_composite_listener.._listen_for_typesi-- D/0t33T:t335EF$$99FDHH-uf  r2r)rrrkr5rgrh)rcontainsrrl)rs r0_setup_composite_listenerrs3  >>&"57G H V02BC Ir2ceZdZdZddZer!e d ddZeddZdddZndZddZdd Z eredd Z edd Z d dd Z nd Z ddZ ddZ e ddZd dZ d!dZy)" 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` cRtj||||jy)z4Detect dictionary set events and emit change events.N)rB __setitem__rr/r7r8s r0rzMutableDict.__setitem__-s sE* r2NcyrIrxrs r0 setdefaultzMutableDict.setdefault5sr2cyrIrxrs r0rzMutableDict.setdefault:s;>r2cyrIrxrs r0rzMutableDict.setdefault=sr2cRtj|g|}|j|SrI)rBrrr/argresults r0rzMutableDict.setdefaultAs#__T0C0F LLNMr2cPtj|||jy)z4Detect dictionary del events and emit change events.N)rB __delitem__r)r/r7s r0rzMutableDict.__delitem__Fs s# r2cVtj|g|i||jyrI)rBupdater)r/akws r0rzMutableDict.updateKs! D#1## r2cyrIrx)r/_MutableDict__keys r0rQzMutableDict.popQs*-r2cyrIrxr/r_MutableDict__defaults r0rQzMutableDict.popTsDGr2cyrIrxrs r0rQzMutableDict.popWsr2cRtj|g|}|j|SrI)rBrQrrs r0rQzMutableDict.pop]s#XXd)S)F LLNMr2cPtj|}|j|SrI)rBpopitemr)r/rs r0rzMutableDict.popitembsd#  r2cNtj||jyrI)rBclearrr.s r0rzMutableDict.clearg 4 r2czt||s.t|tr||Stj||S|S)z3Convert plain dictionary to instance of this class.)rPrBrzr:r6r7r8s r0r:zMutableDict.coerceks8%%%&5z!>>#u- -Lr2ct|SrI)rBr.s r0 __getstate__zMutableDict.__getstate__us Dzr2c&|j|yrIrr/rDs r0 __setstate__zMutableDict.__setstate__xs Er2)r7r(r8r)rgrhrI)r/zMutableDict[_KT, Optional[_T]]r7r(r8rhrgz Optional[_T])r7r(r8r)rgr))r7r(r8objectrgr)r7r(rgrh)rrrr)rgrh)rr(rgr))rr(r_VT | _Trgr)rr(rz_VT | _T | Nonergr)rgzTuple[_KT, _VT]r)r7ror8rrgzMutableDict[_KT, _VT] | None)rgzDict[_KT, _VT])rDz%Union[Dict[str, int], Dict[str, str]]rgrh)rsrtrurvrrr rrrrQrrrwr:rrrxr2r0rrs,  JN 0 7: CG      > >K    - - G G<@  )8       : r2rceZdZdZ ddZddZ ddZddZddZddZ ddZ dd Z dd Z dd Z dd Zdd ZddZe ddZy) 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` c2|jt|ffSrI __class__rXr/protos r0 __reduce_ex__zMutableList.__reduce_ex__d ..r2c||ddyrIrxrs r0rzMutableList.__setstate__s Qr2cRtj||||jy)z.Detect list set events and emit change events.N)rXrr)r/indexr8s r0rzMutableList.__setitem__s ue, r2cPtj|||jy)z.Detect list del events and emit change events.N)rXrr)r/rs r0rzMutableList.__delitem__s u% r2cRtj|g|}|j|SrI)rXrQrrs r0rQzMutableList.pops#$%%  r2cPtj|||jyrI)rXrYrr/xs r0rYzMutableList.append D! r2cPtj|||jyrI)rXextendrrs r0rzMutableList.extendrr2c(|j||SrI)rrs r0__iadd__zMutableList.__iadd__s A r2cRtj||||jyrI)rXinsertr)r/irs r0rzMutableList.inserts D!Q r2cPtj|||jyrI)rXremover)r/rs r0rzMutableList.removerr2cNtj||jyrI)rXrrr.s r0rzMutableList.clearrr2c Ptj|fi||jyrI)rXsortr)r/rs r0rzMutableList.sorts $" r2cNtj||jyrI)rXreverserr.s r0rzMutableList.reverses T r2czt||s.t|tr||Stj||S|S)z-Convert plain list to instance of this class.)rPrXrzr:rs r0r:zMutableList.coerces8 %%%&5z!>>#u- -Lr2Nrr'rgzTuple[type, Tuple[List[int]]]rD Iterable[_T]rgrh)rSupportsIndex | slicer8z_T | Iterable[_T]rgrh)rrrgrh)rr'rgr)rrrgrh)rrrgrh)rrrgzMutableList[_T])rr'rrrgrh)rrrgrhr)rrrgrh)r7ror8zMutableList[_T] | _TrgzOptional[MutableList[_T]])rsrtrurvrrrrrQrYrrrrrrrrwr:rxr2r0rr~s,/"/ &/*3D     2  "  r2rceZdZdZddZddZddZddZddZddZ ddZ dd Z dd Z dd Z dd Zdd ZddZeddZddZddZ ddZy) 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` cPtj|g||jyrI)rdrrr/rs r0rzMutableSet.updates 4# r2cPtj|g||jyrI)rdintersection_updaterrs r0rzMutableSet.intersection_updates +s+ r2cPtj|g||jyrI)rddifference_updaterrs r0r zMutableSet.difference_updates d)S) r2cPtj|g||jyrI)rdsymmetric_difference_updaterrs r0r z&MutableSet.symmetric_difference_updates ''3s3 r2c(|j||SrIrr/others r0__ior__zMutableSet.__ior__s E r2c(|j||SrI)rrs r0__iand__zMutableSet.__iand__ s   ' r2c(|j||SrI)r rs r0__ixor__zMutableSet.__ixor__ s ((/ r2c(|j||SrI)r rs r0__isub__zMutableSet.__isub__s u% r2cPtj|||jyrI)rdaddrr/elems r0rzMutableSet.adds d r2cPtj|||jyrI)rdrrrs r0rzMutableSet.removes 4 r2cPtj|||jyrI)rddiscardrrs r0rzMutableSet.discards D$ r2cRtj|g|}|j|SrI)rdrQrrs r0rQzMutableSet.pop!s#$$  r2cNtj||jyrI)rdrrr.s r0rzMutableSet.clear&s $ r2czt||s.t|tr||Stj||S|S)z,Convert plain set to instance of this class.)rPrdrzr:)r6rr8s r0r:zMutableSet.coerce*s8%%%%5z!>>%/ /Lr2ct|SrI)rdr.s r0rzMutableSet.__getstate__4s 4yr2c&|j|yrIrrs r0rzMutableSet.__setstate__7s Er2c2|jt|ffSrIrrs r0rzMutableSet.__reduce_ex__:rr2N)rrrgrh)rrirgrh)rzAbstractSet[_T]rgMutableSet[_T])rzAbstractSet[object]rgr$)rrrgrh)rrrgrr)rror8rrgzOptional[MutableSet[_T]])rgzSet[_T]rr)rsrtrurvrrr r rrrrrrrrQrrwr:rrrrxr2r0rrs{. /"/ &/r2rr)@rv __future__r collectionsrtypingrrrrr r r r r rrrr-rrrrormr orm._typingrrrorm.attributesrrrr orm.contextr orm.decl_apir orm.stater orm.unitofworkr! sql._typingr"sql.baser# sql.schemar$ sql.type_apir%utilr& util.typingr'r(r)r+rzrrrrrrxr2r0r6sqf ## %-0*2/&8%+-(%$' en env v rGkGT8{82 D e'4S>eP\'48\~`/#b'`/r2