Mutation Tracking

Provide support for tracking of in-place changes to scalar values, which are propagated into ORM change events on owning parent objects.

Establishing Mutability on Scalar Column Values

A typical example of a “mutable” structure is a Python dictionary. Following the example introduced in Column and Data Types, we begin with a custom type that marshals Python dictionaries into JSON strings before being persisted:

  1. from sqlalchemy.types import TypeDecorator, VARCHAR
  2. import json
  3. class JSONEncodedDict(TypeDecorator):
  4. "Represents an immutable structure as a json-encoded string."
  5. impl = VARCHAR
  6. def process_bind_param(self, value, dialect):
  7. if value is not None:
  8. value = json.dumps(value)
  9. return value
  10. def process_result_value(self, value, dialect):
  11. if value is not None:
  12. value = json.loads(value)
  13. return value

The usage of json is only for the purposes of example. The sqlalchemy.ext.mutable extension can be used with any type whose target Python type may be mutable, including PickleType, ARRAY, etc.

When using the sqlalchemy.ext.mutable extension, the value itself tracks all parents which reference it. Below, we illustrate a simple version of the MutableDict dictionary object, which applies the Mutable mixin to a plain Python dictionary:

  1. from sqlalchemy.ext.mutable import Mutable
  2. class MutableDict(Mutable, dict):
  3. @classmethod
  4. def coerce(cls, key, value):
  5. "Convert plain dictionaries to MutableDict."
  6. if not isinstance(value, MutableDict):
  7. if isinstance(value, dict):
  8. return MutableDict(value)
  9. # this call will raise ValueError
  10. return Mutable.coerce(key, value)
  11. else:
  12. return value
  13. def __setitem__(self, key, value):
  14. "Detect dictionary set events and emit change events."
  15. dict.__setitem__(self, key, value)
  16. self.changed()
  17. def __delitem__(self, key):
  18. "Detect dictionary del events and emit change events."
  19. dict.__delitem__(self, key)
  20. 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 Mutable.changed() method is called whenever an in-place change to the datastructure takes place.

We also redefine the 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 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 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:

  1. from sqlalchemy import Table, Column, Integer
  2. my_data = Table('my_data', metadata,
  3. Column('id', Integer, primary_key=True),
  4. Column('data', MutableDict.as_mutable(JSONEncodedDict))
  5. )

Above, 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:

  1. from sqlalchemy import mapper
  2. class MyDataClass(object):
  3. pass
  4. # associates mutation listeners with MyDataClass.data
  5. mapper(MyDataClass, my_data)

The MyDataClass.data member will now be notified of in place changes to its value.

There’s no difference in usage when using declarative:

  1. from sqlalchemy.ext.declarative import declarative_base
  2. Base = declarative_base()
  3. class MyDataClass(Base):
  4. __tablename__ = 'my_data'
  5. id = Column(Integer, primary_key=True)
  6. data = Column(MutableDict.as_mutable(JSONEncodedDict))

Any in-place changes to the MyDataClass.data member will flag the attribute as “dirty” on the parent object:

  1. >>> from sqlalchemy.orm import Session
  2. >>> sess = Session()
  3. >>> m1 = MyDataClass(data={'value1':'foo'})
  4. >>> sess.add(m1)
  5. >>> sess.commit()
  6. >>> m1.data['value1'] = 'bar'
  7. >>> assert m1 in sess.dirty
  8. True

The MutableDict can be associated with all future instances of JSONEncodedDict in one step, using Mutable.associate_with(). This is similar to Mutable.as_mutable() except it will intercept all occurrences of MutableDict in all mappings unconditionally, without the need to declare it individually:

  1. MutableDict.associate_with(JSONEncodedDict)
  2. class MyDataClass(Base):
  3. __tablename__ = 'my_data'
  4. id = Column(Integer, primary_key=True)
  5. data = Column(JSONEncodedDict)

Supporting Pickling

The key to the 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 MutableBase._parents() collection from the pickle stream:

  1. class MyMutableType(Mutable):
  2. def __getstate__(self):
  3. d = self.__dict__.copy()
  4. d.pop('_parents', None)
  5. return d

With our dictionary example, we need to return the contents of the dict itself (and also restore them on __setstate__):

  1. class MutableDict(Mutable, dict):
  2. # ....
  3. def __getstate__(self):
  4. return dict(self)
  5. def __setstate__(self, state):
  6. 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 Mutable mixin will re-establish the Mutable._parents collection on each value object as the owning parents themselves are unpickled.

Receiving Events

The 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 flag_modified() function is called from within the mutable extension:

  1. from sqlalchemy.ext.declarative import declarative_base
  2. from sqlalchemy import event
  3. Base = declarative_base()
  4. class MyDataClass(Base):
  5. __tablename__ = 'my_data'
  6. id = Column(Integer, primary_key=True)
  7. data = Column(MutableDict.as_mutable(JSONEncodedDict))
  8. @event.listens_for(MyDataClass.data, "modified")
  9. def modified_json(instance):
  10. print("json value modified:", instance.data)

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 Composite Column Types.

As is the case with Mutable, the user-defined composite class subclasses MutableComposite as a mixin, and detects and delivers change events to its parents via the MutableComposite.changed() method. In the case of a composite class, the detection is usually via the usage of Python descriptors (i.e. @property), or alternatively via the special Python method __setattr__(). Below we expand upon the Point class introduced in Composite Column Types to subclass MutableComposite and to also route attribute set events via __setattr__ to the MutableComposite.changed() method:

  1. from sqlalchemy.ext.mutable import MutableComposite
  2. class Point(MutableComposite):
  3. def __init__(self, x, y):
  4. self.x = x
  5. self.y = y
  6. def __setattr__(self, key, value):
  7. "Intercept set events"
  8. # set the attribute
  9. object.__setattr__(self, key, value)
  10. # alert all parents to the change
  11. self.changed()
  12. def __composite_values__(self):
  13. return self.x, self.y
  14. def __eq__(self, other):
  15. return isinstance(other, Point) and \
  16. other.x == self.x and \
  17. other.y == self.y
  18. def __ne__(self, other):
  19. return not self.__eq__(other)

The MutableComposite class uses a Python metaclass to automatically establish listeners for any usage of 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:

  1. from sqlalchemy.orm import composite, mapper
  2. from sqlalchemy import Table, Column
  3. vertices = Table('vertices', metadata,
  4. Column('id', Integer, primary_key=True),
  5. Column('x1', Integer),
  6. Column('y1', Integer),
  7. Column('x2', Integer),
  8. Column('y2', Integer),
  9. )
  10. class Vertex(object):
  11. pass
  12. mapper(Vertex, vertices, properties={
  13. 'start': composite(Point, vertices.c.x1, vertices.c.y1),
  14. 'end': composite(Point, vertices.c.x2, vertices.c.y2)
  15. })

Any in-place changes to the Vertex.start or Vertex.end members will flag the attribute as “dirty” on the parent object:

  1. >>> from sqlalchemy.orm import Session
  2. >>> sess = Session()
  3. >>> v1 = Vertex(start=Point(3, 4), end=Point(12, 15))
  4. >>> sess.add(v1)
  5. >>> sess.commit()
  6. >>> v1.end.x = 8
  7. >>> assert v1 in sess.dirty
  8. True

Coercing Mutable Composites

The MutableBase.coerce() method is also supported on composite types. In the case of MutableComposite, the MutableBase.coerce() method is only called for attribute set operations, not load operations. Overriding the MutableBase.coerce() method is essentially equivalent to using a validates() validation routine for all attributes which make use of the custom composite type:

  1. class Point(MutableComposite):
  2. # other Point methods
  3. # ...
  4. def coerce(cls, key, value):
  5. if isinstance(value, tuple):
  6. value = Point(*value)
  7. elif not isinstance(value, Point):
  8. raise ValueError("tuple or Point expected")
  9. return value

Supporting Pickling

As is the case with Mutable, the MutableComposite helper class uses a weakref.WeakKeyDictionary available via the 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:

  1. class Point(MutableComposite):
  2. # ...
  3. def __getstate__(self):
  4. return self.x, self.y
  5. def __setstate__(self, state):
  6. self.x, self.y = state

As with Mutable, the MutableComposite augments the pickling process of the parent’s object-relational state so that the MutableBase._parents() collection is restored to all Point objects.

API Reference

Object NameDescription

Mutable

Mixin that defines transparent propagation of change events to a parent object.

MutableBase

Common base class to Mutable and MutableComposite.

MutableComposite

Mixin that defines transparent propagation of change events on a SQLAlchemy “composite” object to its owning parent or parents.

MutableDict

A dictionary type that implements Mutable.

MutableList

A list type that implements Mutable.

MutableSet

A set type that implements Mutable.

class sqlalchemy.ext.mutable.``MutableBase

Common base class to Mutable and MutableComposite.

  • attribute sqlalchemy.ext.mutable.MutableBase._parents

    Dictionary of parent object’s 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.

    Changed in version 1.4: the InstanceState is now used as the key in the weak dictionary rather than the instance itself.

  • method sqlalchemy.ext.mutable.MutableBase.classmethod coerce(key, value)

    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 Mutable or of type 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 composite() construct handle coercion during load operations.

    • Parameters

      • key – string name of the ORM-mapped attribute being set.

      • value – the incoming value.

      Returns

      the method should return the coerced value, or raise ValueError if the coercion cannot be completed.

class sqlalchemy.ext.mutable.``Mutable

Mixin that defines transparent propagation of change events to a parent object.

See the example in Establishing Mutability on Scalar Column Values for usage information.

Class signature

class sqlalchemy.ext.mutable.Mutable (sqlalchemy.ext.mutable.MutableBase)

  • method sqlalchemy.ext.mutable.Mutable.classmethod _get_listen_keys(attribute)

    inherited from the sqlalchemy.ext.mutable.MutableBase._get_listen_keys method of MutableBase

    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 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 InstanceEvents.refresh() and 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.

    New in version 1.0.5.

  • method sqlalchemy.ext.mutable.Mutable.classmethod _listen_on_attribute(attribute, coerce, parent_cls)

    inherited from the sqlalchemy.ext.mutable.MutableBase._listen_on_attribute method of MutableBase

    Establish this type as a mutation listener for the given mapped descriptor.

  • attribute sqlalchemy.ext.mutable.Mutable._parents

    inherited from the sqlalchemy.ext.mutable.MutableBase._parents attribute of MutableBase

    Dictionary of parent object’s 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.

    Changed in version 1.4: the InstanceState is now used as the key in the weak dictionary rather than the instance itself.

  • method sqlalchemy.ext.mutable.Mutable.classmethod as_mutable(sqltype)

    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 as_mutable() can be used inline:

    1. Table('mytable', metadata,
    2. Column('id', Integer, primary_key=True),
    3. Column('data', MyMutableType.as_mutable(PickleType))
    4. )

    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 Mutable.associate_with() classmethod of the particular 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 as_mutable() for types that are permanent to an application, not with ad-hoc types else this will cause unbounded growth in memory usage.

  • method sqlalchemy.ext.mutable.Mutable.classmethod associate_with(sqltype)

    Associate 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 associate_with() for types that are permanent to an application, not with ad-hoc types else this will cause unbounded growth in memory usage.

  • method sqlalchemy.ext.mutable.Mutable.classmethod associate_with_attribute(attribute)

    Establish this type as a mutation listener for the given mapped descriptor.

  • method sqlalchemy.ext.mutable.Mutable.changed()

    Subclasses should call this method whenever change events occur.

  • method sqlalchemy.ext.mutable.Mutable.classmethod coerce(key, value)

    inherited from the MutableBase.coerce() method of MutableBase

    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 Mutable or of type 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 composite() construct handle coercion during load operations.

    • Parameters

      • key – string name of the ORM-mapped attribute being set.

      • value – the incoming value.

      Returns

      the method should return the coerced value, or raise ValueError if the coercion cannot be completed.

class sqlalchemy.ext.mutable.``MutableComposite

Mixin that defines transparent propagation of change events on a SQLAlchemy “composite” object to its owning parent or parents.

See the example in Establishing Mutability on Composites for usage information.

Class signature

class sqlalchemy.ext.mutable.MutableComposite (sqlalchemy.ext.mutable.MutableBase)

class sqlalchemy.ext.mutable.``MutableDict

A dictionary type that implements Mutable.

The 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 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 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.

See also

MutableList

MutableSet

Class signature

class sqlalchemy.ext.mutable.MutableDict (sqlalchemy.ext.mutable.Mutable, builtins.dict)

  • method sqlalchemy.ext.mutable.MutableDict.clear() → None. Remove all items from D.

  • method sqlalchemy.ext.mutable.MutableDict.classmethod coerce(key, value)

    Convert plain dictionary to instance of this class.

  • method sqlalchemy.ext.mutable.MutableDict.pop(k[, d]) → v, remove specified key and return the corresponding value.

    If key is not found, d is returned if given, otherwise KeyError is raised

  • method sqlalchemy.ext.mutable.MutableDict.popitem() → (k, v), remove and return some (key, value) pair as a

    2-tuple; but raise KeyError if D is empty.

  • method sqlalchemy.ext.mutable.MutableDict.setdefault(key, value)

    Insert key with a value of default if key is not in the dictionary.

    Return the value for key if key is in the dictionary, else default.

  • method sqlalchemy.ext.mutable.MutableDict.update([E, ]\*F*) → None. Update D from dict/iterable E and F.

    If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

class sqlalchemy.ext.mutable.``MutableList(iterable=(), /)

A list type that implements Mutable.

The 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 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 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.

New in version 1.1.

See also

MutableDict

MutableSet

Class signature

class sqlalchemy.ext.mutable.MutableList (sqlalchemy.ext.mutable.Mutable, builtins.list)

class sqlalchemy.ext.mutable.``MutableSet

A set type that implements Mutable.

The 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 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 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.

New in version 1.1.

See also

MutableDict

MutableList

Class signature

class sqlalchemy.ext.mutable.MutableSet (sqlalchemy.ext.mutable.Mutable, builtins.set)