[Sqlalchemy-tickets] Issue #3303: Add a 'changed' event for sqlalchemy.ext.mutable attributes (zzze
Brought to you by:
zzzeek
|
From: zoomorph <iss...@bi...> - 2015-02-05 18:23:06
|
New issue 3303: Add a 'changed' event for sqlalchemy.ext.mutable attributes https://bitbucket.org/zzzeek/sqlalchemy/issue/3303/add-a-changed-event-for zoomorph: Listening for changes to a scalar attribute can be done via the 'set' event: ``` #!python def validate_phone(target, value, oldvalue, initiator): """Strip non-numeric characters from a phone number""" return re.sub(r'(?![0-9])', '', value) # setup listener on UserContact.phone attribute, instructing # it to use the return value listen(UserContact.phone, 'set', validate_phone, retval=True) ``` When Mutable attributes are set, they also emit the 'set' event. However, they do not emit any events when they are merely changed. A new event such as 'changed' should be added to cover this case. It would work like so: ``` #!python def favorites_changed(target, value, oldvalue, initiator): logger.info("Favorites was set or changed") # do something # setup listeners on UserContact.favorites attribute (a MutableList for example) listen(UserContact.favorites, 'set', favorites_changed) listen(UserContact.favorites, 'changed', favorites_changed) u = session.query(UserContact).first() u.favorites = [1, 2, 3] # emits 'set' u.favorites.append(4) # should emit 'changed' u.favorites[-1] = 5 # should emit 'changed' ``` Related to issue #3297 |