# SQLAlchemy 0.9 Documentation

Search:
Release: 0.9.3 | Release Date: February 19, 2014

# ORM Events

The ORM includes a wide variety of hooks available for subscription.

New in version 0.7: The event supercedes the previous system of “extension” classes.

For an introduction to the event API, see Events. Non-ORM events such as those regarding connections and low-level statement execution are described in Core Events.

## Attribute Events

class `sqlalchemy.orm.events.``AttributeEvents`

  Bases: `sqlalchemy.event.base.Events`

  Define events for object attributes.

  These are typically defined on the class-bound descriptor for the target class.

  e.g.:

      from sqlalchemy import event

      def my_append_listener(target, value, initiator):
          print "received append event for target: %s" % target

      event.listen(MyClass.collection, 'append', my_append_listener)

  Listeners have the option to return a possibly modified version of the value, when the `retval=True` flag is passed to `listen()`:

      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)

  A validation function like the above can also raise an exception such as `ValueError` to halt the operation.

  Several modifiers are available to the `listen()` function.

  Parameters: | active_history=False – When True, indicates that the “set” event would like to receive the “old” value being replaced unconditionally, even if this requires firing off database loads. Note that `active_history` can also be set directly via `column_property()` and `relationship()`. propagate=False – When True, the listener function will be established not just for the class attribute given, but for attributes of the same name on all current subclasses of that class, as well as all future subclasses of that class, using an additional listener that listens for instrumentation events. raw=False – When True, the “target” argument to the event will be the `InstanceState` management object, rather than the mapped instance itself. retval=False – when True, the user-defined event listening must return the “value” argument from the function. This gives the listening function the opportunity to change the value that is ultimately used for a “set” or “append” event.

  `append`(target, value, initiator)

    Receive a collection append event.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass.some_attribute, 'append')
        def receive_append(target, value, initiator):
            "listen for the 'append' event"

            # ... (event handling logic) ...

    Parameters: | target – the object instance receiving the event. If the listener is registered with `raw=True`, this will be the `InstanceState` object. value – the value being appended. If this listener is registered with `retval=True`, the listener function must return this value, or a new value which replaces it. initiator – An instance of `attributes.Event` representing the initiation of the event. May be modified from it’s original value by backref handlers in order to control chained event propagation. Changed in version 0.9.0: the `initiator` argument is now passed as a `attributes.Event` object, and may be modified by backref handlers within a chain of backref-linked events.
    Returns: | if the event was registered with `retval=True`, the given value, or a new effective value, should be returned.

  `remove`(target, value, initiator)

    Receive a collection remove event.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass.some_attribute, 'remove')
        def receive_remove(target, value, initiator):
            "listen for the 'remove' event"

            # ... (event handling logic) ...

    Parameters: | target – the object instance receiving the event. If the listener is registered with `raw=True`, this will be the `InstanceState` object. value – the value being removed. initiator – An instance of `attributes.Event` representing the initiation of the event. May be modified from it’s original value by backref handlers in order to control chained event propagation. Changed in version 0.9.0: the `initiator` argument is now passed as a `attributes.Event` object, and may be modified by backref handlers within a chain of backref-linked events.
    Returns: | No return value is defined for this event.

  `set`(target, value, oldvalue, initiator)

    Receive a scalar set event.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass.some_attribute, 'set')
        def receive_set(target, value, oldvalue, initiator):
            "listen for the 'set' event"

            # ... (event handling logic) ...

        # named argument style (new in 0.9)
        @event.listens_for(SomeClass.some_attribute, 'set', named=True)
        def receive_set(**kw):
            "listen for the 'set' event"
            target = kw['target']
            value = kw['value']

            # ... (event handling logic) ...

    Parameters: | target – the object instance receiving the event. If the listener is registered with `raw=True`, this will be the `InstanceState` object. value – the value being set. If this listener is registered with `retval=True`, the listener function must return this value, or a new value which replaces it. oldvalue – the previous value being replaced. This may also be the symbol `NEVER_SET` or `NO_VALUE`. If the listener is registered with `active_history=True`, the previous value of the attribute will be loaded from the database if the existing value is currently unloaded or expired. initiator – An instance of `attributes.Event` representing the initiation of the event. May be modified from it’s original value by backref handlers in order to control chained event propagation. Changed in version 0.9.0: the `initiator` argument is now passed as a `attributes.Event` object, and may be modified by backref handlers within a chain of backref-linked events.
    Returns: | if the event was registered with `retval=True`, the given value, or a new effective value, should be returned.

## Mapper Events

class `sqlalchemy.orm.events.``MapperEvents`

  Bases: `sqlalchemy.event.base.Events`

  Define events specific to mappings.

  e.g.:

      from sqlalchemy import event

      def my_before_insert_listener(mapper, connection, target):
          # execute a stored procedure upon INSERT,
          # apply the value to the row to be inserted
          target.calculated_value = connection.scalar(
                                      "select my_special_function(%d)"
                                      % target.special_number)

      # associate the listener function with SomeClass,
      # to execute during the "before_insert" hook
      event.listen(
          SomeClass, 'before_insert', my_before_insert_listener)

  Available targets include:

  - mapped classes
  - unmapped superclasses of mapped or to-be-mapped classes (using the `propagate=True` flag)
  - `Mapper` objects
  - the `Mapper` class itself and the `mapper()` function indicate listening for all mappers.

  Changed in version 0.8.0: mapper events can be associated with unmapped superclasses of mapped classes.

  Mapper events provide hooks into critical sections of the mapper, including those related to object instrumentation, object loading, and object persistence. In particular, the persistence methods `before_insert()`, and `before_update()` are popular places to augment the state being persisted - however, these methods operate with several significant restrictions. The user is encouraged to evaluate the `SessionEvents.before_flush()` and `SessionEvents.after_flush()` methods as more flexible and user-friendly hooks in which to apply additional database state during a flush.

  When using `MapperEvents`, several modifiers are available to the `event.listen()` function.

  Parameters: | propagate=False – When True, the event listener should be applied to all inheriting mappers and/or the mappers of inheriting classes, as well as any mapper which is the target of this listener. raw=False – When True, the “target” argument passed to applicable event listener functions will be the instance’s `InstanceState` management object, rather than the mapped instance itself. retval=False – when True, the user-defined event function must have a return value, the purpose of which is either to control subsequent event propagation, or to otherwise alter the operation in progress by the mapper. Possible return values are: `sqlalchemy.orm.interfaces.EXT_CONTINUE` - continue event processing normally. `sqlalchemy.orm.interfaces.EXT_STOP` - cancel all subsequent event handlers in the chain. other values - the return value specified by specific listeners, such as `translate_row()` or `create_instance()`.

  `after_configured`()

    Called after a series of mappers have been configured.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass, 'after_configured')
        def receive_after_configured():
            "listen for the 'after_configured' event"

            # ... (event handling logic) ...

    This corresponds to the `orm.configure_mappers()` call, which note is usually called automatically as mappings are first used.

    Theoretically this event is called once per application, but is actually called any time new mappers have been affected by a `orm.configure_mappers()` call. If new mappings are constructed after existing ones have already been used, this event can be called again.

  `after_delete`(mapper, connection, target)

    Receive an object instance after a DELETE statement has been emitted corresponding to that instance.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass, 'after_delete')
        def receive_after_delete(mapper, connection, target):
            "listen for the 'after_delete' event"

            # ... (event handling logic) ...

    This event is used to emit additional SQL statements on the given connection as well as to perform application specific bookkeeping related to a deletion event.

    The event is often called for a batch of objects of the same class after their DELETE statements have been emitted at once in a previous step.

    Warning

    Mapper-level flush events are designed to operate on attributes local to the immediate object being handled and via SQL operations with the given `Connection` only. Handlers here should not make alterations to the state of the `Session` overall, and in general should not affect any `relationship()` -mapped attributes, as session cascade rules will not function properly, nor is it always known if the related class has already been handled. Operations that are not supported in mapper events include:

    - `Session.add()`
    - `Session.delete()`
    - Mapped collection append, add, remove, delete, discard, etc.
    - Mapped relationship attribute set/del events, i.e. `someobject.related = someotherobject`

    Operations which manipulate the state of the object relative to other objects are better handled:

    - In the `__init__()` method of the mapped object itself, or another method designed to establish some particular state.
    - In a `@validates` handler, see Simple Validators
    - Within the `SessionEvents.before_flush()` event.

    Parameters: | mapper – the `Mapper` which is the target of this event. connection – the `Connection` being used to emit DELETE statements for this instance. This provides a handle into the current transaction on the target database specific to this instance. target – the mapped instance being deleted. If the event is configured with `raw=True`, this will instead be the `InstanceState` state-management object associated with the instance.
    Returns: | No return value is supported by this event.

  `after_insert`(mapper, connection, target)

    Receive an object instance after an INSERT statement is emitted corresponding to that instance.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass, 'after_insert')
        def receive_after_insert(mapper, connection, target):
            "listen for the 'after_insert' event"

            # ... (event handling logic) ...

    This event is used to modify in-Python-only state on the instance after an INSERT occurs, as well as to emit additional SQL statements on the given connection.

    The event is often called for a batch of objects of the same class after their INSERT statements have been emitted at once in a previous step. In the extremely rare case that this is not desirable, the `mapper()` can be configured with `batch=False`, which will cause batches of instances to be broken up into individual (and more poorly performing) event->persist->event steps.

    Warning

    Mapper-level flush events are designed to operate on attributes local to the immediate object being handled and via SQL operations with the given `Connection` only. Handlers here should not make alterations to the state of the `Session` overall, and in general should not affect any `relationship()` -mapped attributes, as session cascade rules will not function properly, nor is it always known if the related class has already been handled. Operations that are not supported in mapper events include:

    - `Session.add()`
    - `Session.delete()`
    - Mapped collection append, add, remove, delete, discard, etc.
    - Mapped relationship attribute set/del events, i.e. `someobject.related = someotherobject`

    Operations which manipulate the state of the object relative to other objects are better handled:

    - In the `__init__()` method of the mapped object itself, or another method designed to establish some particular state.
    - In a `@validates` handler, see Simple Validators
    - Within the `SessionEvents.before_flush()` event.

    Parameters: | mapper – the `Mapper` which is the target of this event. connection – the `Connection` being used to emit INSERT statements for this instance. This provides a handle into the current transaction on the target database specific to this instance. target – the mapped instance being persisted. If the event is configured with `raw=True`, this will instead be the `InstanceState` state-management object associated with the instance.
    Returns: | No return value is supported by this event.

  `after_update`(mapper, connection, target)

    Receive an object instance after an UPDATE statement is emitted corresponding to that instance.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass, 'after_update')
        def receive_after_update(mapper, connection, target):
            "listen for the 'after_update' event"

            # ... (event handling logic) ...

    This event is used to modify in-Python-only state on the instance after an UPDATE occurs, as well as to emit additional SQL statements on the given connection.

    This method is called for all instances that are marked as “dirty”, even those which have no net changes to their column-based attributes, and for which no UPDATE statement has proceeded. An object is marked as dirty when any of its column-based attributes have a “set attribute” operation called or when any of its collections are modified. If, at update time, no column-based attributes have any net changes, no UPDATE statement will be issued. This means that an instance being sent to `after_update()` is not a guarantee that an UPDATE statement has been issued.

    To detect if the column-based attributes on the object have net changes, and therefore resulted in an UPDATE statement, use `object_session(instance).is_modified(instance, include_collections=False)`.

    The event is often called for a batch of objects of the same class after their UPDATE statements have been emitted at once in a previous step. In the extremely rare case that this is not desirable, the `mapper()` can be configured with `batch=False`, which will cause batches of instances to be broken up into individual (and more poorly performing) event->persist->event steps.

    Warning

    Mapper-level flush events are designed to operate on attributes local to the immediate object being handled and via SQL operations with the given `Connection` only. Handlers here should not make alterations to the state of the `Session` overall, and in general should not affect any `relationship()` -mapped attributes, as session cascade rules will not function properly, nor is it always known if the related class has already been handled. Operations that are not supported in mapper events include:

    - `Session.add()`
    - `Session.delete()`
    - Mapped collection append, add, remove, delete, discard, etc.
    - Mapped relationship attribute set/del events, i.e. `someobject.related = someotherobject`

    Operations which manipulate the state of the object relative to other objects are better handled:

    - In the `__init__()` method of the mapped object itself, or another method designed to establish some particular state.
    - In a `@validates` handler, see Simple Validators
    - Within the `SessionEvents.before_flush()` event.

    Parameters: | mapper – the `Mapper` which is the target of this event. connection – the `Connection` being used to emit UPDATE statements for this instance. This provides a handle into the current transaction on the target database specific to this instance. target – the mapped instance being persisted. If the event is configured with `raw=True`, this will instead be the `InstanceState` state-management object associated with the instance.
    Returns: | No return value is supported by this event.

  `append_result`(mapper, context, row, target, result, **flags)

    Receive an object instance before that instance is appended to a result list.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass, 'append_result')
        def receive_append_result(mapper, context, row, target, result, **kw):
            "listen for the 'append_result' event"

            # ... (event handling logic) ...

        # named argument style (new in 0.9)
        @event.listens_for(SomeClass, 'append_result', named=True)
        def receive_append_result(**kw):
            "listen for the 'append_result' event"
            mapper = kw['mapper']
            context = kw['context']

            # ... (event handling logic) ...

    This is a rarely used hook which can be used to alter the construction of a result list returned by `Query`.

    Parameters: | mapper – the `Mapper` which is the target of this event. context – the `QueryContext`, which includes a handle to the current `Query` in progress as well as additional state information. row – the result row being handled. This may be an actual `RowProxy` or may be a dictionary containing `Column` objects as keys. target – the mapped instance being populated. If the event is configured with `raw=True`, this will instead be the `InstanceState` state-management object associated with the instance. result – a list-like object where results are being appended. **flags – Additional state information about the current handling of the row.
    Returns: | If this method is registered with `retval=True`, a return value of `EXT_STOP` will prevent the instance from being appended to the given result list, whereas a return value of `EXT_CONTINUE` will result in the default behavior of appending the value to the result list.

  `before_configured`()

    Called before a series of mappers have been configured.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass, 'before_configured')
        def receive_before_configured():
            "listen for the 'before_configured' event"

            # ... (event handling logic) ...

    This corresponds to the `orm.configure_mappers()` call, which note is usually called automatically as mappings are first used.

    Theoretically this event is called once per application, but is actually called any time new mappers are to be affected by a `orm.configure_mappers()` call. If new mappings are constructed after existing ones have already been used, this event can be called again.

    New in version 0.9.3.

  `before_delete`(mapper, connection, target)

    Receive an object instance before a DELETE statement is emitted corresponding to that instance.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass, 'before_delete')
        def receive_before_delete(mapper, connection, target):
            "listen for the 'before_delete' event"

            # ... (event handling logic) ...

    This event is used to emit additional SQL statements on the given connection as well as to perform application specific bookkeeping related to a deletion event.

    The event is often called for a batch of objects of the same class before their DELETE statements are emitted at once in a later step.

    Warning

    Mapper-level flush events are designed to operate on attributes local to the immediate object being handled and via SQL operations with the given `Connection` only. Handlers here should not make alterations to the state of the `Session` overall, and in general should not affect any `relationship()` -mapped attributes, as session cascade rules will not function properly, nor is it always known if the related class has already been handled. Operations that are not supported in mapper events include:

    - `Session.add()`
    - `Session.delete()`
    - Mapped collection append, add, remove, delete, discard, etc.
    - Mapped relationship attribute set/del events, i.e. `someobject.related = someotherobject`

    Operations which manipulate the state of the object relative to other objects are better handled:

    - In the `__init__()` method of the mapped object itself, or another method designed to establish some particular state.
    - In a `@validates` handler, see Simple Validators
    - Within the `SessionEvents.before_flush()` event.

    Parameters: | mapper – the `Mapper` which is the target of this event. connection – the `Connection` being used to emit DELETE statements for this instance. This provides a handle into the current transaction on the target database specific to this instance. target – the mapped instance being deleted. If the event is configured with `raw=True`, this will instead be the `InstanceState` state-management object associated with the instance.
    Returns: | No return value is supported by this event.

  `before_insert`(mapper, connection, target)

    Receive an object instance before an INSERT statement is emitted corresponding to that instance.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass, 'before_insert')
        def receive_before_insert(mapper, connection, target):
            "listen for the 'before_insert' event"

            # ... (event handling logic) ...

    This event is used to modify local, non-object related attributes on the instance before an INSERT occurs, as well as to emit additional SQL statements on the given connection.

    The event is often called for a batch of objects of the same class before their INSERT statements are emitted at once in a later step. In the extremely rare case that this is not desirable, the `mapper()` can be configured with `batch=False`, which will cause batches of instances to be broken up into individual (and more poorly performing) event->persist->event steps.

    Warning

    Mapper-level flush events are designed to operate on attributes local to the immediate object being handled and via SQL operations with the given `Connection` only. Handlers here should not make alterations to the state of the `Session` overall, and in general should not affect any `relationship()` -mapped attributes, as session cascade rules will not function properly, nor is it always known if the related class has already been handled. Operations that are not supported in mapper events include:

    - `Session.add()`
    - `Session.delete()`
    - Mapped collection append, add, remove, delete, discard, etc.
    - Mapped relationship attribute set/del events, i.e. `someobject.related = someotherobject`

    Operations which manipulate the state of the object relative to other objects are better handled:

    - In the `__init__()` method of the mapped object itself, or another method designed to establish some particular state.
    - In a `@validates` handler, see Simple Validators
    - Within the `SessionEvents.before_flush()` event.

    Parameters: | mapper – the `Mapper` which is the target of this event. connection – the `Connection` being used to emit INSERT statements for this instance. This provides a handle into the current transaction on the target database specific to this instance. target – the mapped instance being persisted. If the event is configured with `raw=True`, this will instead be the `InstanceState` state-management object associated with the instance.
    Returns: | No return value is supported by this event.

  `before_update`(mapper, connection, target)

    Receive an object instance before an UPDATE statement is emitted corresponding to that instance.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass, 'before_update')
        def receive_before_update(mapper, connection, target):
            "listen for the 'before_update' event"

            # ... (event handling logic) ...

    This event is used to modify local, non-object related attributes on the instance before an UPDATE occurs, as well as to emit additional SQL statements on the given connection.

    This method is called for all instances that are marked as “dirty”, even those which have no net changes to their column-based attributes. An object is marked as dirty when any of its column-based attributes have a “set attribute” operation called or when any of its collections are modified. If, at update time, no column-based attributes have any net changes, no UPDATE statement will be issued. This means that an instance being sent to `before_update()` is not a guarantee that an UPDATE statement will be issued, although you can affect the outcome here by modifying attributes so that a net change in value does exist.

    To detect if the column-based attributes on the object have net changes, and will therefore generate an UPDATE statement, use `object_session(instance).is_modified(instance, include_collections=False)`.

    The event is often called for a batch of objects of the same class before their UPDATE statements are emitted at once in a later step. In the extremely rare case that this is not desirable, the `mapper()` can be configured with `batch=False`, which will cause batches of instances to be broken up into individual (and more poorly performing) event->persist->event steps.

    Warning

    Mapper-level flush events are designed to operate on attributes local to the immediate object being handled and via SQL operations with the given `Connection` only. Handlers here should not make alterations to the state of the `Session` overall, and in general should not affect any `relationship()` -mapped attributes, as session cascade rules will not function properly, nor is it always known if the related class has already been handled. Operations that are not supported in mapper events include:

    - `Session.add()`
    - `Session.delete()`
    - Mapped collection append, add, remove, delete, discard, etc.
    - Mapped relationship attribute set/del events, i.e. `someobject.related = someotherobject`

    Operations which manipulate the state of the object relative to other objects are better handled:

    - In the `__init__()` method of the mapped object itself, or another method designed to establish some particular state.
    - In a `@validates` handler, see Simple Validators
    - Within the `SessionEvents.before_flush()` event.

    Parameters: | mapper – the `Mapper` which is the target of this event. connection – the `Connection` being used to emit UPDATE statements for this instance. This provides a handle into the current transaction on the target database specific to this instance. target – the mapped instance being persisted. If the event is configured with `raw=True`, this will instead be the `InstanceState` state-management object associated with the instance.
    Returns: | No return value is supported by this event.

  `create_instance`(mapper, context, row, class_)

    Receive a row when a new object instance is about to be created from that row.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass, 'create_instance')
        def receive_create_instance(mapper, context, row, class_):
            "listen for the 'create_instance' event"

            # ... (event handling logic) ...

        # named argument style (new in 0.9)
        @event.listens_for(SomeClass, 'create_instance', named=True)
        def receive_create_instance(**kw):
            "listen for the 'create_instance' event"
            mapper = kw['mapper']
            context = kw['context']

            # ... (event handling logic) ...

    The method can choose to create the instance itself, or it can return EXT_CONTINUE to indicate normal object creation should take place. This listener is typically registered with `retval=True`.

    Parameters: | mapper – the `Mapper` which is the target of this event. context – the `QueryContext`, which includes a handle to the current `Query` in progress as well as additional state information. row – the result row being handled. This may be an actual `RowProxy` or may be a dictionary containing `Column` objects as keys. class_ – the mapped class.
    Returns: | When configured with `retval=True`, the return value should be a newly created instance of the mapped class, or `EXT_CONTINUE` indicating that default object construction should take place.

  `instrument_class`(mapper, class_)

    Receive a class when the mapper is first constructed, before instrumentation is applied to the mapped class.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass, 'instrument_class')
        def receive_instrument_class(mapper, class_):
            "listen for the 'instrument_class' event"

            # ... (event handling logic) ...

    This event is the earliest phase of mapper construction. Most attributes of the mapper are not yet initialized.

    This listener can either be applied to the `Mapper` class overall, or to any un-mapped class which serves as a base for classes that will be mapped (using the `propagate=True` flag):

        Base = declarative_base()

        @event.listens_for(Base, "instrument_class", propagate=True)
        def on_new_class(mapper, cls_):
            " ... "

    Parameters: | mapper – the `Mapper` which is the target of this event. class_ – the mapped class.

  `mapper_configured`(mapper, class_)

    Called when the mapper for the class is fully configured.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass, 'mapper_configured')
        def receive_mapper_configured(mapper, class_):
            "listen for the 'mapper_configured' event"

            # ... (event handling logic) ...

    This event is the latest phase of mapper construction, and is invoked when the mapped classes are first used, so that relationships between mappers can be resolved. When the event is called, the mapper should be in its final state.

    While the configuration event normally occurs automatically, it can be forced to occur ahead of time, in the case where the event is needed before any actual mapper usage, by using the `configure_mappers()` function.

    Parameters: | mapper – the `Mapper` which is the target of this event. class_ – the mapped class.

  `populate_instance`(mapper, context, row, target, **flags)

    Receive an instance before that instance has its attributes populated.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass, 'populate_instance')
        def receive_populate_instance(mapper, context, row, target, **kw):
            "listen for the 'populate_instance' event"

            # ... (event handling logic) ...

        # named argument style (new in 0.9)
        @event.listens_for(SomeClass, 'populate_instance', named=True)
        def receive_populate_instance(**kw):
            "listen for the 'populate_instance' event"
            mapper = kw['mapper']
            context = kw['context']

            # ... (event handling logic) ...

    This usually corresponds to a newly loaded instance but may also correspond to an already-loaded instance which has unloaded attributes to be populated. The method may be called many times for a single instance, as multiple result rows are used to populate eagerly loaded collections.

    Most usages of this hook are obsolete. For a generic “object has been newly created from a row” hook, use `InstanceEvents.load()`.

    Parameters: | mapper – the `Mapper` which is the target of this event. context – the `QueryContext`, which includes a handle to the current `Query` in progress as well as additional state information. row – the result row being handled. This may be an actual `RowProxy` or may be a dictionary containing `Column` objects as keys. target – the mapped instance. If the event is configured with `raw=True`, this will instead be the `InstanceState` state-management object associated with the instance.
    Returns: | When configured with `retval=True`, a return value of `EXT_STOP` will bypass instance population by the mapper. A value of `EXT_CONTINUE` indicates that default instance population should take place.

  `translate_row`(mapper, context, row)

    Perform pre-processing on the given result row and return a new row instance.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass, 'translate_row')
        def receive_translate_row(mapper, context, row):
            "listen for the 'translate_row' event"

            # ... (event handling logic) ...

    This listener is typically registered with `retval=True`. It is called when the mapper first receives a row, before the object identity or the instance itself has been derived from that row. The given row may or may not be a `RowProxy` object - it will always be a dictionary-like object which contains mapped columns as keys. The returned object should also be a dictionary-like object which recognizes mapped columns as keys.

    Parameters: | mapper – the `Mapper` which is the target of this event. context – the `QueryContext`, which includes a handle to the current `Query` in progress as well as additional state information. row – the result row being handled. This may be an actual `RowProxy` or may be a dictionary containing `Column` objects as keys.
    Returns: | When configured with `retval=True`, the function should return a dictionary-like row object, or `EXT_CONTINUE`, indicating the original row should be used.

## Instance Events

class `sqlalchemy.orm.events.``InstanceEvents`

  Bases: `sqlalchemy.event.base.Events`

  Define events specific to object lifecycle.

  e.g.:

      from sqlalchemy import event

      def my_load_listener(target, context):
          print "on load!"

      event.listen(SomeClass, 'load', my_load_listener)

  Available targets include:

  - mapped classes
  - unmapped superclasses of mapped or to-be-mapped classes (using the `propagate=True` flag)
  - `Mapper` objects
  - the `Mapper` class itself and the `mapper()` function indicate listening for all mappers.

  Changed in version 0.8.0: instance events can be associated with unmapped superclasses of mapped classes.

  Instance events are closely related to mapper events, but are more specific to the instance and its instrumentation, rather than its system of persistence.

  When using `InstanceEvents`, several modifiers are available to the `event.listen()` function.

  Parameters: | propagate=False – When True, the event listener should be applied to all inheriting classes as well as the class which is the target of this listener. raw=False – When True, the “target” argument passed to applicable event listener functions will be the instance’s `InstanceState` management object, rather than the mapped instance itself.

  `expire`(target, attrs)

    Receive an object instance after its attributes or some subset have been expired.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass, 'expire')
        def receive_expire(target, attrs):
            "listen for the 'expire' event"

            # ... (event handling logic) ...

    ‘keys’ is a list of attribute names. If None, the entire state was expired.

    Parameters: | target – the mapped instance. If the event is configured with `raw=True`, this will instead be the `InstanceState` state-management object associated with the instance. attrs – iterable collection of attribute names which were expired, or None if all attributes were expired.

  `first_init`(manager, cls)

    Called when the first instance of a particular mapping is called.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass, 'first_init')
        def receive_first_init(manager, cls):
            "listen for the 'first_init' event"

            # ... (event handling logic) ...

  `init`(target, args, kwargs)

    Receive an instance when it’s constructor is called.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass, 'init')
        def receive_init(target, args, kwargs):
            "listen for the 'init' event"

            # ... (event handling logic) ...

    This method is only called during a userland construction of an object. It is not called when an object is loaded from the database.

  `init_failure`(target, args, kwargs)

    Receive an instance when it’s constructor has been called, and raised an exception.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass, 'init_failure')
        def receive_init_failure(target, args, kwargs):
            "listen for the 'init_failure' event"

            # ... (event handling logic) ...

    This method is only called during a userland construction of an object. It is not called when an object is loaded from the database.

  `load`(target, context)

    Receive an object instance after it has been created via `__new__`, and after initial attribute population has occurred.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass, 'load')
        def receive_load(target, context):
            "listen for the 'load' event"

            # ... (event handling logic) ...

    This typically occurs when the instance is created based on incoming result rows, and is only called once for that instance’s lifetime.

    Note that during a result-row load, this method is called upon the first row received for this instance. Note that some attributes and collections may or may not be loaded or even initialized, depending on what’s present in the result rows.

    Parameters: | target – the mapped instance. If the event is configured with `raw=True`, this will instead be the `InstanceState` state-management object associated with the instance. context – the `QueryContext` corresponding to the current `Query` in progress. This argument may be `None` if the load does not correspond to a `Query`, such as during `Session.merge()`.

  `pickle`(target, state_dict)

    Receive an object instance when its associated state is being pickled.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass, 'pickle')
        def receive_pickle(target, state_dict):
            "listen for the 'pickle' event"

            # ... (event handling logic) ...

    Parameters: | target – the mapped instance. If the event is configured with `raw=True`, this will instead be the `InstanceState` state-management object associated with the instance. state_dict – the dictionary returned by `InstanceState.__getstate__`, containing the state to be pickled.

  `refresh`(target, context, attrs)

    Receive an object instance after one or more attributes have been refreshed from a query.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass, 'refresh')
        def receive_refresh(target, context, attrs):
            "listen for the 'refresh' event"

            # ... (event handling logic) ...

    Parameters: | target – the mapped instance. If the event is configured with `raw=True`, this will instead be the `InstanceState` state-management object associated with the instance. context – the `QueryContext` corresponding to the current `Query` in progress. attrs – iterable collection of attribute names which were populated, or None if all column-mapped, non-deferred attributes were populated.

  `resurrect`(target)

    Receive an object instance as it is ‘resurrected’ from garbage collection, which occurs when a “dirty” state falls out of scope.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass, 'resurrect')
        def receive_resurrect(target):
            "listen for the 'resurrect' event"

            # ... (event handling logic) ...

    Parameters: | target – the mapped instance. If the event is configured with `raw=True`, this will instead be the `InstanceState` state-management object associated with the instance.

  `unpickle`(target, state_dict)

    Receive an object instance after it’s associated state has been unpickled.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeClass, 'unpickle')
        def receive_unpickle(target, state_dict):
            "listen for the 'unpickle' event"

            # ... (event handling logic) ...

    Parameters: | target – the mapped instance. If the event is configured with `raw=True`, this will instead be the `InstanceState` state-management object associated with the instance. state_dict – the dictionary sent to `InstanceState.__setstate__`, containing the state dictionary which was pickled.

## Session Events

class `sqlalchemy.orm.events.``SessionEvents`

  Bases: `sqlalchemy.event.base.Events`

  Define events specific to `Session` lifecycle.

  e.g.:

      from sqlalchemy import event
      from sqlalchemy.orm import sessionmaker

      def my_before_commit(session):
          print "before commit!"

      Session = sessionmaker()

      event.listen(Session, "before_commit", my_before_commit)

  The `listen()` function will accept `Session` objects as well as the return result of `sessionmaker()` and `scoped_session()`.

  Additionally, it accepts the `Session` class which will apply listeners to all `Session` instances globally.

  `after_attach`(session, instance)

    Execute after an instance is attached to a session.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeSessionOrFactory, 'after_attach')
        def receive_after_attach(session, instance):
            "listen for the 'after_attach' event"

            # ... (event handling logic) ...

    This is called after an add, delete or merge.

    Note

    As of 0.8, this event fires off after the item has been fully associated with the session, which is different than previous releases. For event handlers that require the object not yet be part of session state (such as handlers which may autoflush while the target object is not yet complete) consider the new `before_attach()` event.

    See also

    `before_attach()`

  `after_begin`(session, transaction, connection)

    Execute after a transaction is begun on a connection

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeSessionOrFactory, 'after_begin')
        def receive_after_begin(session, transaction, connection):
            "listen for the 'after_begin' event"

            # ... (event handling logic) ...

    Parameters: | session – The target `Session`. transaction – The `SessionTransaction`. connection – The `Connection` object which will be used for SQL statements.

    See also

    `before_commit()`

    `after_commit()`

    `after_transaction_create()`

    `after_transaction_end()`

  `after_bulk_delete`(delete_context)

    Execute after a bulk delete operation to the session.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style (arguments as of 0.9)
        @event.listens_for(SomeSessionOrFactory, 'after_bulk_delete')
        def receive_after_bulk_delete(delete_context):
            "listen for the 'after_bulk_delete' event"

            # ... (event handling logic) ...

        # legacy calling style (pre-0.9)
        @event.listens_for(SomeSessionOrFactory, 'after_bulk_delete')
        def receive_after_bulk_delete(session, query, query_context, result):
            "listen for the 'after_bulk_delete' event"

            # ... (event handling logic) ...

    Changed in version 0.9: The `after_bulk_delete` event now accepts the arguments `delete_context`. Listener functions which accept the previous argument signature(s) listed above will be automatically adapted to the new signature.

    This is called as a result of the `Query.delete()` method.

    Parameters: | delete_context – a “delete context” object which contains details about the update, including these attributes: `session` - the `Session` involved `query` -the `Query` object that this update operation was called upon. `context` The `QueryContext` object, corresponding to the invocation of an ORM query. `result` the `ResultProxy` returned as a result of the bulk DELETE operation.

  `after_bulk_update`(update_context)

    Execute after a bulk update operation to the session.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style (arguments as of 0.9)
        @event.listens_for(SomeSessionOrFactory, 'after_bulk_update')
        def receive_after_bulk_update(update_context):
            "listen for the 'after_bulk_update' event"

            # ... (event handling logic) ...

        # legacy calling style (pre-0.9)
        @event.listens_for(SomeSessionOrFactory, 'after_bulk_update')
        def receive_after_bulk_update(session, query, query_context, result):
            "listen for the 'after_bulk_update' event"

            # ... (event handling logic) ...

    Changed in version 0.9: The `after_bulk_update` event now accepts the arguments `update_context`. Listener functions which accept the previous argument signature(s) listed above will be automatically adapted to the new signature.

    This is called as a result of the `Query.update()` method.

    Parameters: | update_context – an “update context” object which contains details about the update, including these attributes: `session` - the `Session` involved `query` -the `Query` object that this update operation was called upon. `context` The `QueryContext` object, corresponding to the invocation of an ORM query. `result` the `ResultProxy` returned as a result of the bulk UPDATE operation.

  `after_commit`(session)

    Execute after a commit has occurred.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeSessionOrFactory, 'after_commit')
        def receive_after_commit(session):
            "listen for the 'after_commit' event"

            # ... (event handling logic) ...

    Note

    The `after_commit()` hook is not per-flush, that is, the `Session` can emit SQL to the database many times within the scope of a transaction. For interception of these events, use the `before_flush()`, `after_flush()`, or `after_flush_postexec()` events.

    Note

    The `Session` is not in an active tranasction when the `after_commit()` event is invoked, and therefore can not emit SQL. To emit SQL corresponding to every transaction, use the `before_commit()` event.

    Parameters: | session – The target `Session`.

    See also

    `before_commit()`

    `after_begin()`

    `after_transaction_create()`

    `after_transaction_end()`

  `after_flush`(session, flush_context)

    Execute after flush has completed, but before commit has been called.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeSessionOrFactory, 'after_flush')
        def receive_after_flush(session, flush_context):
            "listen for the 'after_flush' event"

            # ... (event handling logic) ...

    Note that the session’s state is still in pre-flush, i.e. ‘new’, ‘dirty’, and ‘deleted’ lists still show pre-flush state as well as the history settings on instance attributes.

    Parameters: | session – The target `Session`. flush_context – Internal `UOWTransaction` object which handles the details of the flush.

    See also

    `before_flush()`

    `after_flush_postexec()`

  `after_flush_postexec`(session, flush_context)

    Execute after flush has completed, and after the post-exec state occurs.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeSessionOrFactory, 'after_flush_postexec')
        def receive_after_flush_postexec(session, flush_context):
            "listen for the 'after_flush_postexec' event"

            # ... (event handling logic) ...

    This will be when the ‘new’, ‘dirty’, and ‘deleted’ lists are in their final state. An actual commit() may or may not have occurred, depending on whether or not the flush started its own transaction or participated in a larger transaction.

    Parameters: | session – The target `Session`. flush_context – Internal `UOWTransaction` object which handles the details of the flush.

    See also

    `before_flush()`

    `after_flush()`

  `after_rollback`(session)

    Execute after a real DBAPI rollback has occurred.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeSessionOrFactory, 'after_rollback')
        def receive_after_rollback(session):
            "listen for the 'after_rollback' event"

            # ... (event handling logic) ...

    Note that this event only fires when the actual rollback against the database occurs - it does not fire each time the `Session.rollback()` method is called, if the underlying DBAPI transaction has already been rolled back. In many cases, the `Session` will not be in an “active” state during this event, as the current transaction is not valid. To acquire a `Session` which is active after the outermost rollback has proceeded, use the `SessionEvents.after_soft_rollback()` event, checking the `Session.is_active` flag.

    Parameters: | session – The target `Session`.

  `after_soft_rollback`(session, previous_transaction)

    Execute after any rollback has occurred, including “soft” rollbacks that don’t actually emit at the DBAPI level.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeSessionOrFactory, 'after_soft_rollback')
        def receive_after_soft_rollback(session, previous_transaction):
            "listen for the 'after_soft_rollback' event"

            # ... (event handling logic) ...

    This corresponds to both nested and outer rollbacks, i.e. the innermost rollback that calls the DBAPI’s rollback() method, as well as the enclosing rollback calls that only pop themselves from the transaction stack.

    The given `Session` can be used to invoke SQL and `Session.query()` operations after an outermost rollback by first checking the `Session.is_active` flag:

        @event.listens_for(Session, "after_soft_rollback")
        def do_something(session, previous_transaction):
            if session.is_active:
                session.execute("select * from some_table")

    Parameters: | session – The target `Session`. previous_transaction – The `SessionTransaction` transactional marker object which was just closed. The current `SessionTransaction` for the given `Session` is available via the `Session.transaction` attribute.

    New in version 0.7.3.

  `after_transaction_create`(session, transaction)

    Execute when a new `SessionTransaction` is created.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeSessionOrFactory, 'after_transaction_create')
        def receive_after_transaction_create(session, transaction):
            "listen for the 'after_transaction_create' event"

            # ... (event handling logic) ...

    This event differs from `after_begin()` in that it occurs for each `SessionTransaction` overall, as opposed to when transactions are begun on individual database connections. It is also invoked for nested transactions and subtransactions, and is always matched by a corresponding `after_transaction_end()` event (assuming normal operation of the `Session`).

    Parameters: | session – the target `Session`. transaction – the target `SessionTransaction`.

    New in version 0.8.

    See also

    `after_transaction_end()`

  `after_transaction_end`(session, transaction)

    Execute when the span of a `SessionTransaction` ends.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeSessionOrFactory, 'after_transaction_end')
        def receive_after_transaction_end(session, transaction):
            "listen for the 'after_transaction_end' event"

            # ... (event handling logic) ...

    This event differs from `after_commit()` in that it corresponds to all `SessionTransaction` objects in use, including those for nested transactions and subtransactions, and is always matched by a corresponding `after_transaction_create()` event.

    Parameters: | session – the target `Session`. transaction – the target `SessionTransaction`.

    New in version 0.8.

    See also

    `after_transaction_create()`

  `before_attach`(session, instance)

    Execute before an instance is attached to a session.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeSessionOrFactory, 'before_attach')
        def receive_before_attach(session, instance):
            "listen for the 'before_attach' event"

            # ... (event handling logic) ...

    This is called before an add, delete or merge causes the object to be part of the session.

    New in version 0.8.: Note that `after_attach()` now fires off after the item is part of the session. `before_attach()` is provided for those cases where the item should not yet be part of the session state.

    See also

    `after_attach()`

  `before_commit`(session)

    Execute before commit is called.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeSessionOrFactory, 'before_commit')
        def receive_before_commit(session):
            "listen for the 'before_commit' event"

            # ... (event handling logic) ...

    Note

    The `before_commit()` hook is not per-flush, that is, the `Session` can emit SQL to the database many times within the scope of a transaction. For interception of these events, use the `before_flush()`, `after_flush()`, or `after_flush_postexec()` events.

    Parameters: | session – The target `Session`.

    See also

    `after_commit()`

    `after_begin()`

    `after_transaction_create()`

    `after_transaction_end()`

  `before_flush`(session, flush_context, instances)

    Execute before flush process has started.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeSessionOrFactory, 'before_flush')
        def receive_before_flush(session, flush_context, instances):
            "listen for the 'before_flush' event"

            # ... (event handling logic) ...

    Parameters: | session – The target `Session`. flush_context – Internal `UOWTransaction` object which handles the details of the flush. instances – Usually `None`, this is the collection of objects which can be passed to the `Session.flush()` method (note this usage is deprecated).

    See also

    `after_flush()`

    `after_flush_postexec()`

## Instrumentation Events

Defines SQLAlchemy’s system of class instrumentation.

This module is usually not directly visible to user applications, but defines a large part of the ORM’s interactivity.

instrumentation.py deals with registration of end-user classes for state tracking. It interacts closely with state.py and attributes.py which establish per-instance and per-class-attribute instrumentation, respectively.

The class instrumentation system can be customized on a per-class or global basis using the `sqlalchemy.ext.instrumentation` module, which provides the means to build and specify alternate instrumentation forms.

class `sqlalchemy.orm.events.``InstrumentationEvents`

  Bases: `sqlalchemy.event.base.Events`

  Events related to class instrumentation events.

  The listeners here support being established against any new style class, that is any object that is a subclass of ‘type’. Events will then be fired off for events against that class. If the “propagate=True” flag is passed to event.listen(), the event will fire off for subclasses of that class as well.

  The Python `type` builtin is also accepted as a target, which when used has the effect of events being emitted for all classes.

  Note the “propagate” flag here is defaulted to `True`, unlike the other class level events where it defaults to `False`. This means that new subclasses will also be the subject of these events, when a listener is established on a superclass.

  Changed in version 0.8: - events here will emit based on comparing the incoming class to the type of class passed to `event.listen()`. Previously, the event would fire for any class unconditionally regardless of what class was sent for listening, despite documentation which stated the contrary.

  `attribute_instrument`(cls, key, inst)

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeBaseClass, 'attribute_instrument')
        def receive_attribute_instrument(cls, key, inst):
            "listen for the 'attribute_instrument' event"

            # ... (event handling logic) ...

    Called when an attribute is instrumented.

  `class_instrument`(cls)

    Called after the given class is instrumented.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeBaseClass, 'class_instrument')
        def receive_class_instrument(cls):
            "listen for the 'class_instrument' event"

            # ... (event handling logic) ...

    To get at the `ClassManager`, use `manager_of_class()`.

  `class_uninstrument`(cls)

    Called before the given class is uninstrumented.

    Example argument forms:

        from sqlalchemy import event

        # standard decorator style
        @event.listens_for(SomeBaseClass, 'class_uninstrument')
        def receive_class_uninstrument(cls):
            "listen for the 'class_uninstrument' event"

            # ... (event handling logic) ...

    To get at the `ClassManager`, use `manager_of_class()`.