Sh3ll
OdayForums


Server : LiteSpeed
System : Linux premium84.web-hosting.com 4.18.0-553.44.1.lve.el8.x86_64 #1 SMP Thu Mar 13 14:29:12 UTC 2025 x86_64
User : claqxcrl ( 523)
PHP Version : 8.1.32
Disable Function : NONE
Directory :  /opt/hc_python/lib64/python3.12/site-packages/sqlalchemy/ext/__pycache__/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : //opt/hc_python/lib64/python3.12/site-packages/sqlalchemy/ext/__pycache__/mutable.cpython-312.pyc
�

���g�����dZddlmZddlmZddlmZddlmZddlmZddlm	Z	ddlm
Z
dd	lmZdd
lmZddlm
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&l2m3Z3dd'lm4Z4dd(l5m6Z6dd)l5m7Z7ed*�Z8ed+�Z9Gd,�d-�Z:Gd.�d/e:�Z;Gd0�d1e:�Z<d9d2�Z=e=�Gd3�d4e;ee8e9f�Z>Gd5�d6e;e
e�Z?Gd7�d8e;e
e�Z@y):a�3Provide 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)�_TypeEngineArgument)�SchemaEventTarget)�Column)�
TypeEngine)�memoized_property)�
SupportsIndex)�	TypeGuard�_KT�_VTc�h�eZdZdZedd��Zedd��Zed	d��Ze								d
d��Z	y)�MutableBasezPCommon base class to :class:`.Mutable`
    and :class:`.MutableComposite`.

    c�*�tj�S)a�Dictionary 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.

        )�weakrefr��selfs �G/opt/hc_python/lib64/python3.12/site-packages/sqlalchemy/ext/mutable.py�_parentszMutableBase._parents�s���(�(�*�*�c�>�|�yd}t||t|�fz��)a�Given 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)�
ValueError�type)�cls�key�value�msgs    r2�coercezMutableBase.coerce�s*��0�=��A�����T�%�[�1�1�2�2r4c��|jhS)a�Given 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.

        )r9�r8�	attributes  r2�_get_listen_keyszMutableBase._get_listen_keys�s��"�
�
��r4c�l����	�
�|j�||jury|j}�j|��	d���fd��
								d�	�
fd�}										d��fd�}						d�fd�}						d�fd�}tj|d�
dd�	�tj|d
�
dd�	�tj|d|dd�	�tj|d|dd�	�tj|d
|ddd��tj|d|dd�	�tj|d|dd�	�y)�]Establish this type as a mutation listener for the given
        mapped descriptor.

        Nc���|jj�d�}|�3�r!�j�|�}||j�<�|j|<yy)z�Listen for objects loaded or refreshed.

            Wrap the target data member's value with
            ``Mutable``.

            N)�dict�getr<r3)�state�args�valr8r<r9s   ���r2�loadz.MutableBase._listen_on_attribute.<locals>.loadsQ����*�*�.�.��d�+�C�����*�*�S�#�.�C�&)�E�J�J�s�O�&)����U�#�	r4c�>��|r�j|�r	�|�yy�N)�intersection)rF�ctx�attrs�listen_keysrIs   ��r2�
load_attrsz4MutableBase._listen_on_attribute.<locals>.load_attrss!���
�K�4�4�U�;��U��<r4c����||ur|St|��s�j�|�}|��|j|<t|��r%|jjt	|�d�|S)z�Listen 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<r3�popr)�targetr:�oldvalue�	initiatorr8r9s    ��r2�set_z.MutableBase._listen_on_attribute.<locals>.set_si����� ����e�S�)��
�
�3��.��� �),����v�&��(�C�(��!�!�%�%�g�f�o�t�<��Lr4c���|jj�d�}|�.d|vrtt�|d<|d�j	|�yy�Nzext.mutable.values)rDrEr�list�append)rF�
state_dictrHr9s   �r2�picklez0MutableBase._listen_on_attribute.<locals>.pickle3sT����*�*�.�.��d�+�C���'�z�9�7B�4�7H�J�3�4��/�0��5�<�<�S�A�r4c���d|vrI|d}t|t�r|D]}�|j|<�y|d�D]}�|j|<�yyrY)rRrZr3)rFr\�
collectionrHr9s    �r2�unpicklez2MutableBase._listen_on_attribute.<locals>.unpickle<se���$�z�1�'�(<�=�
��j�$�/�)��.1����U�+� *� *�*>�?��D��.1����U�+� E�2r4�_sa_event_merge_wo_loadT)�raw�	propagaterI�refresh�
refresh_flush�set)rb�retvalrcr]r`)rF�InstanceState[_O]rGr�return�None)rFrhrMz+Union[object, QueryContext, UOWTransaction]rN�
Iterable[Any]rirj)
rTrhr:�MutableBase | NonerUrlrVrrirl)rFrhr\zDict[str, Any]rirj)r9�class_r@r�listen)r8r?r<�
parent_clsrPrWr]r`r9rOrIs` `     @@@r2�_listen_on_attributez MutableBase._listen_on_attribute�s�����m�m���Y�-�-�-���%�%�
��*�*�9�5��	*�	�$�	�<�	�!�	��		�	�%�	�%�	�)�	�+�		�
 �	�2	B�$�	B�2@�	B�
�	B�	2�$�	2�2@�	2�
�	2�	����%����	
�	���Z���4�4�H�
����	�:�4�4�	
�	��������	
�	����u�d��T�T�	
�	���Z��6�t�t�L�
����
�H�$�$�	
r4N)rizWeakKeyDictionary[Any, Any])r9�strr:rriz
Optional[Any])r?�QueryableAttribute[Any]ri�Set[str])r?rrr<�boolroz_ExternalEntityType[Any]rirj)
�__name__�
__module__�__qualname__�__doc__r'r3�classmethodr<r@rp�r4r2r-r-�s����
�+��+� �3��3�8����$�m
�*�m
��m
�-�	m
�

�m
��m
r4r-c�V�eZdZdZdd�Ze				dd��Zed	d��Zed
d��Zy)�Mutablez�Mixin that defines transparent propagation of change
    events to a parent object.

    See the example in :ref:`mutable_scalars` for usage information.

    c�|�|jj�D]\}}t|j�|��!y�z@Subclasses should call this method whenever change events occur.N)r3�itemsr�obj)r1�parentr9s   r2�changedzMutable.changedis/�� �=�=�.�.�0�K�F�C��&�*�*�,��,�1r4c�>�|j|d|j�y)rBTN)rprmr>s  r2�associate_with_attributez Mutable.associate_with_attributeos��	� � ��D�)�2B�2B�Cr4c�L���d��fd�}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|jdj��s�'�jt
||j���My)Nr)�non_primary�column_attrsrR�columnsr7r��getattrr9)�mapperrm�propr8�sqltypes   ��r2�listen_for_typez/Mutable.associate_with.<locals>.listen_for_type�sP����!�!���+�+���d�l�l�1�o�2�2�G�<��0�0������1J�K�,r4�mapper_configuredN)r�z
Mapper[_O]rmr7rirj)rrnr)r8r�r�s`` r2�associate_withzMutable.associate_withys���$	L�	���V�0�/�Br4c�����tj���t�t�r&t	j
�d�						dd��}d�nd�						d���fd�}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)�sqltypr�s  r2�_add_column_memoz,Mutable.as_mutable.<locals>._add_column_memo�s��
9?����4�5r4TFc����|jryd}|jD]�}t|jt�s��r'|jj
j
d��us|jj�us�`|jj
j
|d�r��d|jj
|<�jt||j����y)N�_ext_mutable_listener_appliedr�FT)r�r�rR�
expressionr%r�rEr7r�r�r9)r�rm�_APPLIED_KEYr�r8�schema_event_checkr�s    ���r2r�z+Mutable.as_mutable.<locals>.listen_for_type�s�����!�!��:�L��+�+��
�t����7�/� $��� 4� 4� 8� 8� 8�!� '�!'�
 �?�?�/�/�7�:� �?�?�/�/�3�3�L�%�H�=A����,�,�\�:��4�4�W�V�T�X�X�5N�O�',r4r�)r�zTypeEngine[Any]r�z
Column[_T]rirj)r��
Mapper[_T]rmz*Union[DeclarativeAttributeIntercept, type]rirj)r�to_instancerRr$r�listens_forrnr)r8r�r�r�r�s``  @r2�
as_mutablezMutable.as_mutable�s����F�#�#�G�,��
�g�0�1�
�
�
�w�(>�
?�
?�'�
?�"�
?��
?�@�
?�"&��!&��	P��	P�>�	P��	P�:	���V�0�/�B��r4N�rirj)r?zInstrumentedAttribute[_O]rirj)r�r7rirj)r�z_TypeEngineArgument[_T]rizTypeEngine[_T])	rurvrwrxr�ryr�r�r�rzr4r2r|r|as`���-��D�1�D�	
�D��D��C��C�4�S��Sr4r|c�*�eZdZdZedd��Zdd�Zy)�MutableCompositez�Mixin 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.

    c�b�|jhj|jj�SrK)r9�union�property�_attribute_keysr>s  r2r@z!MutableComposite._get_listen_keys�s%���
�
��$�$�Y�%7�%7�%G�%G�H�Hr4c��|jj�D]h\}}|jj|�}t	|j|�|j�D] \}}t|j�||��"�jyr~)	r3rr��get_property�zip�_composite_values_from_instancer��setattrr�)r1r�r9r�r:�	attr_names      r2r�zMutableComposite.changed�sr�� �=�=�.�.�0�K�F�C��=�=�-�-�c�2�D�$'��4�4�T�:��$�$�%� ��y���
�
��i��7�	%�1r4N)r?zQueryableAttribute[_O]rirsr�)rurvrwrxryr@r�rzr4r2r�r��s"����I��I�	8r4r�c�z�dd�}tjtd|�stjtd|�yy)Nc��|jD]v}t|d�s�t|jt�s�+t|jt�s�F|jjt||j�d|��xy)N�composite_classF)
�iterate_properties�hasattrrRr�r7�
issubclassr�rpr�r9)r�rmr�s   r2�_listen_for_typez3_setup_composite_listener.<locals>._listen_for_typesd���-�-�D���/�0��t�3�3�T�:��t�3�3�5E�F��$�$�9�9��F�D�H�H�-�u�f��
.r4r�)r�r�rmr7rirj)r�containsrrn)r�s r2�_setup_composite_listenerr�s3��	��>�>�&�"5�7G�H�
���V�0�2B�C�Ir4c���eZdZdZd�fd�Zer!e	d							dd��Zedd��Zddd�Zn�fd�Zd�fd�Zd�fd�Z	eredd	��Z
edd
��Z
	d					dd�Z
n�fd�Z
d�fd
�Zd�fd�Ze
dd��Zdd�Z				d d�Z�xZS)!�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`

    c�F��t�|�||�|j�y)z4Detect dictionary set events and emit change events.N)�super�__setitem__r�)r1r9r:�	__class__s   �r2r�zMutableDict.__setitem__.s���
���C��'����r4c��yrKrz�r1r9r:s   r2�
setdefaultzMutableDict.setdefault6s��r4c��yrKrzr�s   r2r�zMutableDict.setdefault;s��;>r4c��yrKrzr�s   r2r�zMutableDict.setdefault>s��r4c�@��t�|�|�}|j�|SrK)r�r�r��r1�arg�resultr�s   �r2r�zMutableDict.setdefaultBs ����W�'��-�F��L�L�N��Mr4c�D��t�|�|�|j�y)z4Detect dictionary del events and emit change events.N�r��__delitem__r�)r1r9r�s  �r2r�zMutableDict.__delitem__Gs���
���C� ����r4c�D��t�|�|i|��|j�yrK�r��updater�)r1�a�kwr�s   �r2r�zMutableDict.updateLs���
���� �R� ����r4c��yrKrz)r1�_MutableDict__keys  r2rSzMutableDict.popRs��*-r4c��yrKrz�r1r��_MutableDict__defaults   r2rSzMutableDict.popUs��DGr4c��yrKrzr�s   r2rSzMutableDict.popXs��r4c�@��t�|�|�}|j�|SrK�r�rSr�r�s   �r2rSzMutableDict.pop^s����W�[�#�&�F��L�L�N��Mr4c�D��t�|��}|j�|SrK)r��popitemr�)r1r�r�s  �r2r�zMutableDict.popitemcs������"�������
r4c�B��t�|��|j�yrK�r��clearr��r1r�s �r2r�zMutableDict.clearh����
��
�����r4c�z�t||�s.t|t�r||�Stj||�S|S)z3Convert plain dictionary to instance of this class.)rRrDr|r<�r8r9r:s   r2r<zMutableDict.coercels8���%��%��%��&��5�z�!��>�>�#�u�-�-��Lr4c��t|�SrK)rDr0s r2�__getstate__zMutableDict.__getstate__vs���D�z�r4c�&�|j|�yrK�r��r1rFs  r2�__setstate__zMutableDict.__setstate__ys��	
���E�r4)r9r*r:r+rirjrK)r1zMutableDict[_KT, Optional[_T]]r9r*r:rjrizOptional[_T])r9r*r:r+rir+)r9r*r:�objectrir�)r9r*rirj)r�rr�r+rirj)r�r*rir+)r�r*r��_VT | _Trir�)r�r*r�z_VT | _T | Nonerir�)rizTuple[_KT, _VT]r�)r9rqr:rrizMutableDict[_KT, _VT] | None)rizDict[_KT, _VT])rFz%Union[Dict[str, int], Dict[str, str]]rirj)rurvrwrxr�rrr�r�r�rSr�r�ryr<r�r��
__classcell__�r�s@r2r�r�s�����,�
�
�JN�	�0�	�7:�	�CG�	�
�	�
�	�
�>�
�>�K�	�
�
��	�-�
�-�	�G�
�G�<@�	��	�)8�	�
�	�	�
�
�������:��	
�r4r�c����eZdZdZ				dd�Zdd�Zdd�Zdd�Z						d�fd�Zd�fd�Z	d�fd�Z
d�fd	�Zd�fd
�Zdd�Z
d�fd�Zd�fd
�Zd�fd�Zd�fd�Zd�fd�Ze						d d��Z�xZS)!�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`

    c�2�|jt|�ffSrK�r�rZ�r1�protos  r2�
__reduce_ex__zMutableList.__reduce_ex__��������d��
�.�.r4c��||ddyrKrzr�s  r2r�zMutableList.__setstate__�s����Q�r4c�.�tj|�SrK�r�is_non_string_iterable�r1r:s  r2�	is_scalarzMutableList.is_scalar�s���.�.�u�5�5�5r4c�,�tj|�SrKr�r�s  r2�is_iterablezMutableList.is_iterable�s���*�*�5�1�1r4c����t|t�r"|j|�rt�|�||�n1t|t
�r!|j
|�rt�|�||�|j�y)z.Detect list set events and emit change events.N)rRr(r�r�r��slicer�r�)r1�indexr:r�s   �r2r�zMutableList.__setitem__�sX����e�]�+����u�0E��G���u�-�
��u�
%�$�*:�*:�5�*A��G���u�-����r4c�D��t�|�|�|j�y)z.Detect list del events and emit change events.Nr�)r1r�r�s  �r2r�zMutableList.__delitem__�s���
���E�"����r4c�@��t�|�|�}|j�|SrKr�r�s   �r2rSzMutableList.pop��������c�"�������
r4c�D��t�|�|�|j�yrK)r�r[r��r1�xr�s  �r2r[zMutableList.append�����
���q�����r4c�D��t�|�|�|j�yrK)r��extendr�rs  �r2rzMutableList.extend�rr4c�(�|j|�|SrK)r)r1rs  r2�__iadd__zMutableList.__iadd__�s�����A���r4c�F��t�|�||�|j�yrK)r��insertr�)r1�irr�s   �r2rzMutableList.insert�s���
���q�!�����r4c�D��t�|�|�|j�yrK�r��remover�)r1r	r�s  �r2rzMutableList.remove�rr4c�B��t�|��|j�yrKr�r�s �r2r�zMutableList.clear�r�r4c�D��t�|�di|��|j�y)Nrz)r��sortr�)r1r�r�s  �r2rzMutableList.sort�s���
����r�����r4c�B��t�|��|j�yrK)r��reverser�r�s �r2rzMutableList.reverse�s���
�������r4c�z�t||�s.t|t�r||�Stj||�S|S)z-Convert plain list to instance of this class.)rRrZr|r<r�s   r2r<zMutableList.coerce�s8��
�%��%��%��&��5�z�!��>�>�#�u�-�-��Lr4�r�r(rizTuple[type, Tuple[List[int]]]�rF�Iterable[_T]rirj)r:�_T | Iterable[_T]riz
TypeGuard[_T])r:rrizTypeGuard[Iterable[_T]])r��SupportsIndex | slicer:rrirj)r�rrirj)r�r(rir)rrrirj)rrrirj)rrrizMutableList[_T])r	r(rrrirj)r	rrirjr�)r�rrirj)r9rqr:zMutableList[_T] | _TrizOptional[MutableList[_T]])rurvrwrxr�r�r�r�r�r�rSr[rrrrr�rrryr<r�r�s@r2r�r�s�����,/�"�/�	&�/��6�2��*��3D��	
���
�
���������	��	�2�	�	"�	��	r4r�c����eZdZdZd�fd�Zd�fd�Zd�fd�Zd�fd�Zdd�Zdd�Z	dd�Z
dd	�Zd�fd
�Zd�fd�Z
d�fd�Zd�fd
�Zd�fd�Zedd��Zdd�Zdd�Z				dd�Z�xZS)�
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`


    c�>��t�|�|�|j�yrKr��r1r�r�s  �r2r�zMutableSet.update�s���
��������r4c�>��t�|�|�|j�yrK)r��intersection_updater�rs  �r2rzMutableSet.intersection_updates���
��#�S�)����r4c�>��t�|�|�|j�yrK)r��difference_updater�rs  �r2rzMutableSet.difference_updates���
��!�3�'����r4c�>��t�|�|�|j�yrK)r��symmetric_difference_updater�rs  �r2r!z&MutableSet.symmetric_difference_updates���
��+�S�1����r4c�(�|j|�|SrKr��r1�others  r2�__ior__zMutableSet.__ior__s�����E���r4c�(�|j|�|SrK)rr#s  r2�__iand__zMutableSet.__iand__s��� � ��'��r4c�(�|j|�|SrK)r!r#s  r2�__ixor__zMutableSet.__ixor__s���(�(��/��r4c�(�|j|�|SrK)rr#s  r2�__isub__zMutableSet.__isub__s�����u�%��r4c�D��t�|�|�|j�yrK)r��addr��r1�elemr�s  �r2r-zMutableSet.adds���
���D�����r4c�D��t�|�|�|j�yrKrr.s  �r2rzMutableSet.remove#s���
���t�����r4c�D��t�|�|�|j�yrK)r��discardr�r.s  �r2r2zMutableSet.discard's���
��������r4c�@��t�|�|�}|j�|SrKr�r�s   �r2rSzMutableSet.pop+r�r4c�B��t�|��|j�yrKr�r�s �r2r�zMutableSet.clear0r�r4c�z�t||�s.t|t�r||�Stj||�S|S)z,Convert plain set to instance of this class.)rRrfr|r<)r8r�r:s   r2r<zMutableSet.coerce4s8���%��%��%��%��5�z�!��>�>�%��/�/��Lr4c��t|�SrK)rfr0s r2r�zMutableSet.__getstate__>s���4�y�r4c�&�|j|�yrKr�r�s  r2r�zMutableSet.__setstate__As�����E�r4c�2�|jt|�ffSrKr�r�s  r2r�zMutableSet.__reduce_ex__Dr�r4)r�rrirj)r�rkrirj)r$zAbstractSet[_T]ri�MutableSet[_T])r$zAbstractSet[object]rir9)r/rrirj)r�rrirr�)r�rqr:rrizOptional[MutableSet[_T]])rizSet[_T]rr)rurvrwrxr�rrr!r%r'r)r+r-rr2rSr�ryr<r�r�r�r�r�s@r2rr�s|����.������������
�������/�"�/�	&�/r4rr�)Arx�
__future__r�collectionsr�typingrrrrr	r
rrr
rrrr/r�rrrr�ormr�orm._typingrrr�orm.attributesrrrr�orm.contextr�orm.decl_apir �	orm.stater!�orm.unitofworkr"�sql._typingr#�sql.baser$�
sql.schemar%�sql.type_apir&r'�util.typingr(r)r*r+r-r|r�r�r�r�rrzr4r2�<module>rJs
��q�f#�#���������� ����%������-���0�*�2�/�&�8�%�+�-�(��%�$�'�#�
�e�n��
�e�n��u
�u
�pG�k�G�T8�{�8�2
D� ��e�'�4��S��>�e�Pe�'�4��8�e�P`/��#�b�'�`/r4

ZeroDay Forums Mini