mutable.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. # ext/mutable.py
  2. # Copyright (C) 2005-2017 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  7. r"""Provide support for tracking of in-place changes to scalar values,
  8. which are propagated into ORM change events on owning parent objects.
  9. .. versionadded:: 0.7 :mod:`sqlalchemy.ext.mutable` replaces SQLAlchemy's
  10. legacy approach to in-place mutations of scalar values; see
  11. :ref:`07_migration_mutation_extension`.
  12. .. _mutable_scalars:
  13. Establishing Mutability on Scalar Column Values
  14. ===============================================
  15. A typical example of a "mutable" structure is a Python dictionary.
  16. Following the example introduced in :ref:`types_toplevel`, we
  17. begin with a custom type that marshals Python dictionaries into
  18. JSON strings before being persisted::
  19. from sqlalchemy.types import TypeDecorator, VARCHAR
  20. import json
  21. class JSONEncodedDict(TypeDecorator):
  22. "Represents an immutable structure as a json-encoded string."
  23. impl = VARCHAR
  24. def process_bind_param(self, value, dialect):
  25. if value is not None:
  26. value = json.dumps(value)
  27. return value
  28. def process_result_value(self, value, dialect):
  29. if value is not None:
  30. value = json.loads(value)
  31. return value
  32. The usage of ``json`` is only for the purposes of example. The
  33. :mod:`sqlalchemy.ext.mutable` extension can be used
  34. with any type whose target Python type may be mutable, including
  35. :class:`.PickleType`, :class:`.postgresql.ARRAY`, etc.
  36. When using the :mod:`sqlalchemy.ext.mutable` extension, the value itself
  37. tracks all parents which reference it. Below, we illustrate a simple
  38. version of the :class:`.MutableDict` dictionary object, which applies
  39. the :class:`.Mutable` mixin to a plain Python dictionary::
  40. from sqlalchemy.ext.mutable import Mutable
  41. class MutableDict(Mutable, dict):
  42. @classmethod
  43. def coerce(cls, key, value):
  44. "Convert plain dictionaries to MutableDict."
  45. if not isinstance(value, MutableDict):
  46. if isinstance(value, dict):
  47. return MutableDict(value)
  48. # this call will raise ValueError
  49. return Mutable.coerce(key, value)
  50. else:
  51. return value
  52. def __setitem__(self, key, value):
  53. "Detect dictionary set events and emit change events."
  54. dict.__setitem__(self, key, value)
  55. self.changed()
  56. def __delitem__(self, key):
  57. "Detect dictionary del events and emit change events."
  58. dict.__delitem__(self, key)
  59. self.changed()
  60. The above dictionary class takes the approach of subclassing the Python
  61. built-in ``dict`` to produce a dict
  62. subclass which routes all mutation events through ``__setitem__``. There are
  63. variants on this approach, such as subclassing ``UserDict.UserDict`` or
  64. ``collections.MutableMapping``; the part that's important to this example is
  65. that the :meth:`.Mutable.changed` method is called whenever an in-place
  66. change to the datastructure takes place.
  67. We also redefine the :meth:`.Mutable.coerce` method which will be used to
  68. convert any values that are not instances of ``MutableDict``, such
  69. as the plain dictionaries returned by the ``json`` module, into the
  70. appropriate type. Defining this method is optional; we could just as well
  71. created our ``JSONEncodedDict`` such that it always returns an instance
  72. of ``MutableDict``, and additionally ensured that all calling code
  73. uses ``MutableDict`` explicitly. When :meth:`.Mutable.coerce` is not
  74. overridden, any values applied to a parent object which are not instances
  75. of the mutable type will raise a ``ValueError``.
  76. Our new ``MutableDict`` type offers a class method
  77. :meth:`~.Mutable.as_mutable` which we can use within column metadata
  78. to associate with types. This method grabs the given type object or
  79. class and associates a listener that will detect all future mappings
  80. of this type, applying event listening instrumentation to the mapped
  81. attribute. Such as, with classical table metadata::
  82. from sqlalchemy import Table, Column, Integer
  83. my_data = Table('my_data', metadata,
  84. Column('id', Integer, primary_key=True),
  85. Column('data', MutableDict.as_mutable(JSONEncodedDict))
  86. )
  87. Above, :meth:`~.Mutable.as_mutable` returns an instance of ``JSONEncodedDict``
  88. (if the type object was not an instance already), which will intercept any
  89. attributes which are mapped against this type. Below we establish a simple
  90. mapping against the ``my_data`` table::
  91. from sqlalchemy import mapper
  92. class MyDataClass(object):
  93. pass
  94. # associates mutation listeners with MyDataClass.data
  95. mapper(MyDataClass, my_data)
  96. The ``MyDataClass.data`` member will now be notified of in place changes
  97. to its value.
  98. There's no difference in usage when using declarative::
  99. from sqlalchemy.ext.declarative import declarative_base
  100. Base = declarative_base()
  101. class MyDataClass(Base):
  102. __tablename__ = 'my_data'
  103. id = Column(Integer, primary_key=True)
  104. data = Column(MutableDict.as_mutable(JSONEncodedDict))
  105. Any in-place changes to the ``MyDataClass.data`` member
  106. will flag the attribute as "dirty" on the parent object::
  107. >>> from sqlalchemy.orm import Session
  108. >>> sess = Session()
  109. >>> m1 = MyDataClass(data={'value1':'foo'})
  110. >>> sess.add(m1)
  111. >>> sess.commit()
  112. >>> m1.data['value1'] = 'bar'
  113. >>> assert m1 in sess.dirty
  114. True
  115. The ``MutableDict`` can be associated with all future instances
  116. of ``JSONEncodedDict`` in one step, using
  117. :meth:`~.Mutable.associate_with`. This is similar to
  118. :meth:`~.Mutable.as_mutable` except it will intercept all occurrences
  119. of ``MutableDict`` in all mappings unconditionally, without
  120. the need to declare it individually::
  121. MutableDict.associate_with(JSONEncodedDict)
  122. class MyDataClass(Base):
  123. __tablename__ = 'my_data'
  124. id = Column(Integer, primary_key=True)
  125. data = Column(JSONEncodedDict)
  126. Supporting Pickling
  127. --------------------
  128. The key to the :mod:`sqlalchemy.ext.mutable` extension relies upon the
  129. placement of a ``weakref.WeakKeyDictionary`` upon the value object, which
  130. stores a mapping of parent mapped objects keyed to the attribute name under
  131. which they are associated with this value. ``WeakKeyDictionary`` objects are
  132. not picklable, due to the fact that they contain weakrefs and function
  133. callbacks. In our case, this is a good thing, since if this dictionary were
  134. picklable, it could lead to an excessively large pickle size for our value
  135. objects that are pickled by themselves outside of the context of the parent.
  136. The developer responsibility here is only to provide a ``__getstate__`` method
  137. that excludes the :meth:`~MutableBase._parents` collection from the pickle
  138. stream::
  139. class MyMutableType(Mutable):
  140. def __getstate__(self):
  141. d = self.__dict__.copy()
  142. d.pop('_parents', None)
  143. return d
  144. With our dictionary example, we need to return the contents of the dict itself
  145. (and also restore them on __setstate__)::
  146. class MutableDict(Mutable, dict):
  147. # ....
  148. def __getstate__(self):
  149. return dict(self)
  150. def __setstate__(self, state):
  151. self.update(state)
  152. In the case that our mutable value object is pickled as it is attached to one
  153. or more parent objects that are also part of the pickle, the :class:`.Mutable`
  154. mixin will re-establish the :attr:`.Mutable._parents` collection on each value
  155. object as the owning parents themselves are unpickled.
  156. .. _mutable_composites:
  157. Establishing Mutability on Composites
  158. =====================================
  159. Composites are a special ORM feature which allow a single scalar attribute to
  160. be assigned an object value which represents information "composed" from one
  161. or more columns from the underlying mapped table. The usual example is that of
  162. a geometric "point", and is introduced in :ref:`mapper_composite`.
  163. .. versionchanged:: 0.7
  164. The internals of :func:`.orm.composite` have been
  165. greatly simplified and in-place mutation detection is no longer enabled by
  166. default; instead, the user-defined value must detect changes on its own and
  167. propagate them to all owning parents. The :mod:`sqlalchemy.ext.mutable`
  168. extension provides the helper class :class:`.MutableComposite`, which is a
  169. slight variant on the :class:`.Mutable` class.
  170. As is the case with :class:`.Mutable`, the user-defined composite class
  171. subclasses :class:`.MutableComposite` as a mixin, and detects and delivers
  172. change events to its parents via the :meth:`.MutableComposite.changed` method.
  173. In the case of a composite class, the detection is usually via the usage of
  174. Python descriptors (i.e. ``@property``), or alternatively via the special
  175. Python method ``__setattr__()``. Below we expand upon the ``Point`` class
  176. introduced in :ref:`mapper_composite` to subclass :class:`.MutableComposite`
  177. and to also route attribute set events via ``__setattr__`` to the
  178. :meth:`.MutableComposite.changed` method::
  179. from sqlalchemy.ext.mutable import MutableComposite
  180. class Point(MutableComposite):
  181. def __init__(self, x, y):
  182. self.x = x
  183. self.y = y
  184. def __setattr__(self, key, value):
  185. "Intercept set events"
  186. # set the attribute
  187. object.__setattr__(self, key, value)
  188. # alert all parents to the change
  189. self.changed()
  190. def __composite_values__(self):
  191. return self.x, self.y
  192. def __eq__(self, other):
  193. return isinstance(other, Point) and \
  194. other.x == self.x and \
  195. other.y == self.y
  196. def __ne__(self, other):
  197. return not self.__eq__(other)
  198. The :class:`.MutableComposite` class uses a Python metaclass to automatically
  199. establish listeners for any usage of :func:`.orm.composite` that specifies our
  200. ``Point`` type. Below, when ``Point`` is mapped to the ``Vertex`` class,
  201. listeners are established which will route change events from ``Point``
  202. objects to each of the ``Vertex.start`` and ``Vertex.end`` attributes::
  203. from sqlalchemy.orm import composite, mapper
  204. from sqlalchemy import Table, Column
  205. vertices = Table('vertices', metadata,
  206. Column('id', Integer, primary_key=True),
  207. Column('x1', Integer),
  208. Column('y1', Integer),
  209. Column('x2', Integer),
  210. Column('y2', Integer),
  211. )
  212. class Vertex(object):
  213. pass
  214. mapper(Vertex, vertices, properties={
  215. 'start': composite(Point, vertices.c.x1, vertices.c.y1),
  216. 'end': composite(Point, vertices.c.x2, vertices.c.y2)
  217. })
  218. Any in-place changes to the ``Vertex.start`` or ``Vertex.end`` members
  219. will flag the attribute as "dirty" on the parent object::
  220. >>> from sqlalchemy.orm import Session
  221. >>> sess = Session()
  222. >>> v1 = Vertex(start=Point(3, 4), end=Point(12, 15))
  223. >>> sess.add(v1)
  224. >>> sess.commit()
  225. >>> v1.end.x = 8
  226. >>> assert v1 in sess.dirty
  227. True
  228. Coercing Mutable Composites
  229. ---------------------------
  230. The :meth:`.MutableBase.coerce` method is also supported on composite types.
  231. In the case of :class:`.MutableComposite`, the :meth:`.MutableBase.coerce`
  232. method is only called for attribute set operations, not load operations.
  233. Overriding the :meth:`.MutableBase.coerce` method is essentially equivalent
  234. to using a :func:`.validates` validation routine for all attributes which
  235. make use of the custom composite type::
  236. class Point(MutableComposite):
  237. # other Point methods
  238. # ...
  239. def coerce(cls, key, value):
  240. if isinstance(value, tuple):
  241. value = Point(*value)
  242. elif not isinstance(value, Point):
  243. raise ValueError("tuple or Point expected")
  244. return value
  245. .. versionadded:: 0.7.10,0.8.0b2
  246. Support for the :meth:`.MutableBase.coerce` method in conjunction with
  247. objects of type :class:`.MutableComposite`.
  248. Supporting Pickling
  249. --------------------
  250. As is the case with :class:`.Mutable`, the :class:`.MutableComposite` helper
  251. class uses a ``weakref.WeakKeyDictionary`` available via the
  252. :meth:`MutableBase._parents` attribute which isn't picklable. If we need to
  253. pickle instances of ``Point`` or its owning class ``Vertex``, we at least need
  254. to define a ``__getstate__`` that doesn't include the ``_parents`` dictionary.
  255. Below we define both a ``__getstate__`` and a ``__setstate__`` that package up
  256. the minimal form of our ``Point`` class::
  257. class Point(MutableComposite):
  258. # ...
  259. def __getstate__(self):
  260. return self.x, self.y
  261. def __setstate__(self, state):
  262. self.x, self.y = state
  263. As with :class:`.Mutable`, the :class:`.MutableComposite` augments the
  264. pickling process of the parent's object-relational state so that the
  265. :meth:`MutableBase._parents` collection is restored to all ``Point`` objects.
  266. """
  267. from ..orm.attributes import flag_modified
  268. from .. import event, types
  269. from ..orm import mapper, object_mapper, Mapper
  270. from ..util import memoized_property
  271. from ..sql.base import SchemaEventTarget
  272. import weakref
  273. class MutableBase(object):
  274. """Common base class to :class:`.Mutable`
  275. and :class:`.MutableComposite`.
  276. """
  277. @memoized_property
  278. def _parents(self):
  279. """Dictionary of parent object->attribute name on the parent.
  280. This attribute is a so-called "memoized" property. It initializes
  281. itself with a new ``weakref.WeakKeyDictionary`` the first time
  282. it is accessed, returning the same object upon subsequent access.
  283. """
  284. return weakref.WeakKeyDictionary()
  285. @classmethod
  286. def coerce(cls, key, value):
  287. """Given a value, coerce it into the target type.
  288. Can be overridden by custom subclasses to coerce incoming
  289. data into a particular type.
  290. By default, raises ``ValueError``.
  291. This method is called in different scenarios depending on if
  292. the parent class is of type :class:`.Mutable` or of type
  293. :class:`.MutableComposite`. In the case of the former, it is called
  294. for both attribute-set operations as well as during ORM loading
  295. operations. For the latter, it is only called during attribute-set
  296. operations; the mechanics of the :func:`.composite` construct
  297. handle coercion during load operations.
  298. :param key: string name of the ORM-mapped attribute being set.
  299. :param value: the incoming value.
  300. :return: the method should return the coerced value, or raise
  301. ``ValueError`` if the coercion cannot be completed.
  302. """
  303. if value is None:
  304. return None
  305. msg = "Attribute '%s' does not accept objects of type %s"
  306. raise ValueError(msg % (key, type(value)))
  307. @classmethod
  308. def _get_listen_keys(cls, attribute):
  309. """Given a descriptor attribute, return a ``set()`` of the attribute
  310. keys which indicate a change in the state of this attribute.
  311. This is normally just ``set([attribute.key])``, but can be overridden
  312. to provide for additional keys. E.g. a :class:`.MutableComposite`
  313. augments this set with the attribute keys associated with the columns
  314. that comprise the composite value.
  315. This collection is consulted in the case of intercepting the
  316. :meth:`.InstanceEvents.refresh` and
  317. :meth:`.InstanceEvents.refresh_flush` events, which pass along a list
  318. of attribute names that have been refreshed; the list is compared
  319. against this set to determine if action needs to be taken.
  320. .. versionadded:: 1.0.5
  321. """
  322. return set([attribute.key])
  323. @classmethod
  324. def _listen_on_attribute(cls, attribute, coerce, parent_cls):
  325. """Establish this type as a mutation listener for the given
  326. mapped descriptor.
  327. """
  328. key = attribute.key
  329. if parent_cls is not attribute.class_:
  330. return
  331. # rely on "propagate" here
  332. parent_cls = attribute.class_
  333. listen_keys = cls._get_listen_keys(attribute)
  334. def load(state, *args):
  335. """Listen for objects loaded or refreshed.
  336. Wrap the target data member's value with
  337. ``Mutable``.
  338. """
  339. val = state.dict.get(key, None)
  340. if val is not None:
  341. if coerce:
  342. val = cls.coerce(key, val)
  343. state.dict[key] = val
  344. val._parents[state.obj()] = key
  345. def load_attrs(state, ctx, attrs):
  346. if not attrs or listen_keys.intersection(attrs):
  347. load(state)
  348. def set(target, value, oldvalue, initiator):
  349. """Listen for set/replace events on the target
  350. data member.
  351. Establish a weak reference to the parent object
  352. on the incoming value, remove it for the one
  353. outgoing.
  354. """
  355. if value is oldvalue:
  356. return value
  357. if not isinstance(value, cls):
  358. value = cls.coerce(key, value)
  359. if value is not None:
  360. value._parents[target.obj()] = key
  361. if isinstance(oldvalue, cls):
  362. oldvalue._parents.pop(target.obj(), None)
  363. return value
  364. def pickle(state, state_dict):
  365. val = state.dict.get(key, None)
  366. if val is not None:
  367. if 'ext.mutable.values' not in state_dict:
  368. state_dict['ext.mutable.values'] = []
  369. state_dict['ext.mutable.values'].append(val)
  370. def unpickle(state, state_dict):
  371. if 'ext.mutable.values' in state_dict:
  372. for val in state_dict['ext.mutable.values']:
  373. val._parents[state.obj()] = key
  374. event.listen(parent_cls, 'load', load,
  375. raw=True, propagate=True)
  376. event.listen(parent_cls, 'refresh', load_attrs,
  377. raw=True, propagate=True)
  378. event.listen(parent_cls, 'refresh_flush', load_attrs,
  379. raw=True, propagate=True)
  380. event.listen(attribute, 'set', set,
  381. raw=True, retval=True, propagate=True)
  382. event.listen(parent_cls, 'pickle', pickle,
  383. raw=True, propagate=True)
  384. event.listen(parent_cls, 'unpickle', unpickle,
  385. raw=True, propagate=True)
  386. class Mutable(MutableBase):
  387. """Mixin that defines transparent propagation of change
  388. events to a parent object.
  389. See the example in :ref:`mutable_scalars` for usage information.
  390. """
  391. def changed(self):
  392. """Subclasses should call this method whenever change events occur."""
  393. for parent, key in self._parents.items():
  394. flag_modified(parent, key)
  395. @classmethod
  396. def associate_with_attribute(cls, attribute):
  397. """Establish this type as a mutation listener for the given
  398. mapped descriptor.
  399. """
  400. cls._listen_on_attribute(attribute, True, attribute.class_)
  401. @classmethod
  402. def associate_with(cls, sqltype):
  403. """Associate this wrapper with all future mapped columns
  404. of the given type.
  405. This is a convenience method that calls
  406. ``associate_with_attribute`` automatically.
  407. .. warning::
  408. The listeners established by this method are *global*
  409. to all mappers, and are *not* garbage collected. Only use
  410. :meth:`.associate_with` for types that are permanent to an
  411. application, not with ad-hoc types else this will cause unbounded
  412. growth in memory usage.
  413. """
  414. def listen_for_type(mapper, class_):
  415. for prop in mapper.column_attrs:
  416. if isinstance(prop.columns[0].type, sqltype):
  417. cls.associate_with_attribute(getattr(class_, prop.key))
  418. event.listen(mapper, 'mapper_configured', listen_for_type)
  419. @classmethod
  420. def as_mutable(cls, sqltype):
  421. """Associate a SQL type with this mutable Python type.
  422. This establishes listeners that will detect ORM mappings against
  423. the given type, adding mutation event trackers to those mappings.
  424. The type is returned, unconditionally as an instance, so that
  425. :meth:`.as_mutable` can be used inline::
  426. Table('mytable', metadata,
  427. Column('id', Integer, primary_key=True),
  428. Column('data', MyMutableType.as_mutable(PickleType))
  429. )
  430. Note that the returned type is always an instance, even if a class
  431. is given, and that only columns which are declared specifically with
  432. that type instance receive additional instrumentation.
  433. To associate a particular mutable type with all occurrences of a
  434. particular type, use the :meth:`.Mutable.associate_with` classmethod
  435. of the particular :class:`.Mutable` subclass to establish a global
  436. association.
  437. .. warning::
  438. The listeners established by this method are *global*
  439. to all mappers, and are *not* garbage collected. Only use
  440. :meth:`.as_mutable` for types that are permanent to an application,
  441. not with ad-hoc types else this will cause unbounded growth
  442. in memory usage.
  443. """
  444. sqltype = types.to_instance(sqltype)
  445. # a SchemaType will be copied when the Column is copied,
  446. # and we'll lose our ability to link that type back to the original.
  447. # so track our original type w/ columns
  448. if isinstance(sqltype, SchemaEventTarget):
  449. @event.listens_for(sqltype, "before_parent_attach")
  450. def _add_column_memo(sqltyp, parent):
  451. parent.info['_ext_mutable_orig_type'] = sqltyp
  452. schema_event_check = True
  453. else:
  454. schema_event_check = False
  455. def listen_for_type(mapper, class_):
  456. for prop in mapper.column_attrs:
  457. if (
  458. schema_event_check and
  459. hasattr(prop.expression, 'info') and
  460. prop.expression.info.get('_ext_mutable_orig_type')
  461. is sqltype
  462. ) or (
  463. prop.columns[0].type is sqltype
  464. ):
  465. cls.associate_with_attribute(getattr(class_, prop.key))
  466. event.listen(mapper, 'mapper_configured', listen_for_type)
  467. return sqltype
  468. class MutableComposite(MutableBase):
  469. """Mixin that defines transparent propagation of change
  470. events on a SQLAlchemy "composite" object to its
  471. owning parent or parents.
  472. See the example in :ref:`mutable_composites` for usage information.
  473. """
  474. @classmethod
  475. def _get_listen_keys(cls, attribute):
  476. return set([attribute.key]).union(attribute.property._attribute_keys)
  477. def changed(self):
  478. """Subclasses should call this method whenever change events occur."""
  479. for parent, key in self._parents.items():
  480. prop = object_mapper(parent).get_property(key)
  481. for value, attr_name in zip(
  482. self.__composite_values__(),
  483. prop._attribute_keys):
  484. setattr(parent, attr_name, value)
  485. def _setup_composite_listener():
  486. def _listen_for_type(mapper, class_):
  487. for prop in mapper.iterate_properties:
  488. if (hasattr(prop, 'composite_class') and
  489. isinstance(prop.composite_class, type) and
  490. issubclass(prop.composite_class, MutableComposite)):
  491. prop.composite_class._listen_on_attribute(
  492. getattr(class_, prop.key), False, class_)
  493. if not event.contains(Mapper, "mapper_configured", _listen_for_type):
  494. event.listen(Mapper, 'mapper_configured', _listen_for_type)
  495. _setup_composite_listener()
  496. class MutableDict(Mutable, dict):
  497. """A dictionary type that implements :class:`.Mutable`.
  498. The :class:`.MutableDict` object implements a dictionary that will
  499. emit change events to the underlying mapping when the contents of
  500. the dictionary are altered, including when values are added or removed.
  501. Note that :class:`.MutableDict` does **not** apply mutable tracking to the
  502. *values themselves* inside the dictionary. Therefore it is not a sufficient
  503. solution for the use case of tracking deep changes to a *recursive*
  504. dictionary structure, such as a JSON structure. To support this use case,
  505. build a subclass of :class:`.MutableDict` that provides appropriate
  506. coersion to the values placed in the dictionary so that they too are
  507. "mutable", and emit events up to their parent structure.
  508. .. versionadded:: 0.8
  509. .. seealso::
  510. :class:`.MutableList`
  511. :class:`.MutableSet`
  512. """
  513. def __setitem__(self, key, value):
  514. """Detect dictionary set events and emit change events."""
  515. dict.__setitem__(self, key, value)
  516. self.changed()
  517. def setdefault(self, key, value):
  518. result = dict.setdefault(self, key, value)
  519. self.changed()
  520. return result
  521. def __delitem__(self, key):
  522. """Detect dictionary del events and emit change events."""
  523. dict.__delitem__(self, key)
  524. self.changed()
  525. def update(self, *a, **kw):
  526. dict.update(self, *a, **kw)
  527. self.changed()
  528. def pop(self, *arg):
  529. result = dict.pop(self, *arg)
  530. self.changed()
  531. return result
  532. def popitem(self):
  533. result = dict.popitem(self)
  534. self.changed()
  535. return result
  536. def clear(self):
  537. dict.clear(self)
  538. self.changed()
  539. @classmethod
  540. def coerce(cls, key, value):
  541. """Convert plain dictionary to instance of this class."""
  542. if not isinstance(value, cls):
  543. if isinstance(value, dict):
  544. return cls(value)
  545. return Mutable.coerce(key, value)
  546. else:
  547. return value
  548. def __getstate__(self):
  549. return dict(self)
  550. def __setstate__(self, state):
  551. self.update(state)
  552. class MutableList(Mutable, list):
  553. """A list type that implements :class:`.Mutable`.
  554. The :class:`.MutableList` object implements a list that will
  555. emit change events to the underlying mapping when the contents of
  556. the list are altered, including when values are added or removed.
  557. Note that :class:`.MutableList` does **not** apply mutable tracking to the
  558. *values themselves* inside the list. Therefore it is not a sufficient
  559. solution for the use case of tracking deep changes to a *recursive*
  560. mutable structure, such as a JSON structure. To support this use case,
  561. build a subclass of :class:`.MutableList` that provides appropriate
  562. coersion to the values placed in the dictionary so that they too are
  563. "mutable", and emit events up to their parent structure.
  564. .. versionadded:: 1.1
  565. .. seealso::
  566. :class:`.MutableDict`
  567. :class:`.MutableSet`
  568. """
  569. def __setitem__(self, index, value):
  570. """Detect list set events and emit change events."""
  571. list.__setitem__(self, index, value)
  572. self.changed()
  573. def __setslice__(self, start, end, value):
  574. """Detect list set events and emit change events."""
  575. list.__setslice__(self, start, end, value)
  576. self.changed()
  577. def __delitem__(self, index):
  578. """Detect list del events and emit change events."""
  579. list.__delitem__(self, index)
  580. self.changed()
  581. def __delslice__(self, start, end):
  582. """Detect list del events and emit change events."""
  583. list.__delslice__(self, start, end)
  584. self.changed()
  585. def pop(self, *arg):
  586. result = list.pop(self, *arg)
  587. self.changed()
  588. return result
  589. def append(self, x):
  590. list.append(self, x)
  591. self.changed()
  592. def extend(self, x):
  593. list.extend(self, x)
  594. self.changed()
  595. def insert(self, i, x):
  596. list.insert(self, i, x)
  597. self.changed()
  598. def remove(self, i):
  599. list.remove(self, i)
  600. self.changed()
  601. def clear(self):
  602. list.clear(self)
  603. self.changed()
  604. def sort(self):
  605. list.sort(self)
  606. self.changed()
  607. def reverse(self):
  608. list.reverse(self)
  609. self.changed()
  610. @classmethod
  611. def coerce(cls, index, value):
  612. """Convert plain list to instance of this class."""
  613. if not isinstance(value, cls):
  614. if isinstance(value, list):
  615. return cls(value)
  616. return Mutable.coerce(index, value)
  617. else:
  618. return value
  619. def __getstate__(self):
  620. return list(self)
  621. def __setstate__(self, state):
  622. self[:] = state
  623. class MutableSet(Mutable, set):
  624. """A set type that implements :class:`.Mutable`.
  625. The :class:`.MutableSet` object implements a set that will
  626. emit change events to the underlying mapping when the contents of
  627. the set are altered, including when values are added or removed.
  628. Note that :class:`.MutableSet` does **not** apply mutable tracking to the
  629. *values themselves* inside the set. Therefore it is not a sufficient
  630. solution for the use case of tracking deep changes to a *recursive*
  631. mutable structure. To support this use case,
  632. build a subclass of :class:`.MutableSet` that provides appropriate
  633. coersion to the values placed in the dictionary so that they too are
  634. "mutable", and emit events up to their parent structure.
  635. .. versionadded:: 1.1
  636. .. seealso::
  637. :class:`.MutableDict`
  638. :class:`.MutableList`
  639. """
  640. def update(self, *arg):
  641. set.update(self, *arg)
  642. self.changed()
  643. def intersection_update(self, *arg):
  644. set.intersection_update(self, *arg)
  645. self.changed()
  646. def difference_update(self, *arg):
  647. set.difference_update(self, *arg)
  648. self.changed()
  649. def symmetric_difference_update(self, *arg):
  650. set.symmetric_difference_update(self, *arg)
  651. self.changed()
  652. def add(self, elem):
  653. set.add(self, elem)
  654. self.changed()
  655. def remove(self, elem):
  656. set.remove(self, elem)
  657. self.changed()
  658. def discard(self, elem):
  659. set.discard(self, elem)
  660. self.changed()
  661. def pop(self, *arg):
  662. result = set.pop(self, *arg)
  663. self.changed()
  664. return result
  665. def clear(self):
  666. set.clear(self)
  667. self.changed()
  668. @classmethod
  669. def coerce(cls, index, value):
  670. """Convert plain set to instance of this class."""
  671. if not isinstance(value, cls):
  672. if isinstance(value, set):
  673. return cls(value)
  674. return Mutable.coerce(index, value)
  675. else:
  676. return value
  677. def __getstate__(self):
  678. return set(self)
  679. def __setstate__(self, state):
  680. self.update(state)
  681. def __reduce_ex__(self, proto):
  682. return (self.__class__, (list(self), ))