ORM Events
For an introduction to the most commonly used ORM events, see the section Tracking queries, object and Session Changes with Events. The event system in general is discussed at . Non-ORM events such as those regarding connections and low-level statement execution are described in Core Events.
The most basic event hooks are available at the level of the ORM Session object. The types of things that are intercepted here include:
Persistence Operations - the ORM flush process that sends changes to the database can be extended using events that fire off at different parts of the flush, to augment or modify the data being sent to the database or to allow other things to happen when persistence occurs. Read more about persistence events at .
Object lifecycle events - hooks when objects are added, persisted, deleted from sessions. Read more about these at Object Lifecycle Events.
Execution Events - Part of the execution model, all SELECT statements against ORM entities emitted, as well as bulk UPDATE and DELETE statements outside of the flush process, are intercepted from the Session.execute() method using the method. Read more about this event at Execute Events.
Be sure to read the chapter for context on these events.
class sqlalchemy.orm.SessionEvents
Define events specific to Session lifecycle.
e.g.:
The function will accept Session objects as well as the return result of and scoped_session().
Additionally, it accepts the class which will apply listeners to all Session instances globally.
Parameters:
raw=False –
When True, the “target” argument passed to applicable event listener functions that work on individual objects will be the instance’s management object, rather than the mapped instance itself.
New in version 1.3.14.
restore_load_context=False –
Applies to the SessionEvents.loaded_as_persistent() event. Restores the loader context of the object when the event hook is complete, so that ongoing eager load operations continue to target the object appropriately. A warning is emitted if the object is moved to a new loader context from within this event if this flag is not set.
New in version 1.3.14.
Members
, after_begin(), , after_bulk_update(), , after_flush(), , after_rollback(), , after_transaction_create(), , before_attach(), , before_flush(), , deleted_to_persistent(), , dispatch, , loaded_as_persistent(), , pending_to_transient(), , persistent_to_detached(), , transient_to_pending()
Class signature
class ()
method sqlalchemy.orm.SessionEvents.after_attach(session: , instance: _O) → None
Execute after an instance is attached to a session.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSessionClassOrObject, '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()](#sqlalchemy.orm.SessionEvents.before_attach "sqlalchemy.orm.SessionEvents.before_attach") event.
See also
[SessionEvents.before\_attach()](#sqlalchemy.orm.SessionEvents.before_attach "sqlalchemy.orm.SessionEvents.before_attach")
[Object Lifecycle Events]($a1168341f79cb60a.md#session-lifecycle-events)
method sqlalchemy.orm.SessionEvents.after_begin(session: , transaction: SessionTransaction, connection: ) → None
Execute after a transaction is begun on a connection
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSessionClassOrObject, 'after_begin')
def receive_after_begin(session, transaction, connection):
"listen for the 'after_begin' event"
# ... (event handling logic) ...
```
- Parameters:
- **session** – The target [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session").
- **transaction** – The [SessionTransaction]($694f628462946390.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.SessionTransaction").
- **connection** – The [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object which will be used for SQL statements.
See also
[SessionEvents.before\_commit()](#sqlalchemy.orm.SessionEvents.before_commit "sqlalchemy.orm.SessionEvents.before_commit")
[SessionEvents.after\_commit()](#sqlalchemy.orm.SessionEvents.after_commit "sqlalchemy.orm.SessionEvents.after_commit")
[SessionEvents.after\_transaction\_create()](#sqlalchemy.orm.SessionEvents.after_transaction_create "sqlalchemy.orm.SessionEvents.after_transaction_create")
[SessionEvents.after\_transaction\_end()](#sqlalchemy.orm.SessionEvents.after_transaction_end "sqlalchemy.orm.SessionEvents.after_transaction_end")
method sqlalchemy.orm.SessionEvents.after_bulk_delete(delete_context: _O) → None
Event for after the legacy method has been called.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSessionClassOrObject, 'after_bulk_delete')
def receive_after_bulk_delete(delete_context):
"listen for the 'after_bulk_delete' event"
# ... (event handling logic) ...
# DEPRECATED calling style (pre-0.9, will be removed in a future release)
@event.listens_for(SomeSessionClassOrObject, '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 [SessionEvents.after\_bulk\_delete()](#sqlalchemy.orm.SessionEvents.after_bulk_delete "sqlalchemy.orm.SessionEvents.after_bulk_delete") event now accepts the arguments [SessionEvents.after\_bulk\_delete.delete\_context](#sqlalchemy.orm.SessionEvents.after_bulk_delete.params.delete_context "sqlalchemy.orm.SessionEvents.after_bulk_delete"). Support for listener functions which accept the previous argument signature(s) listed above as “deprecated” will be removed in a future release.
Legacy Feature
The [SessionEvents.after\_bulk\_delete()](#sqlalchemy.orm.SessionEvents.after_bulk_delete "sqlalchemy.orm.SessionEvents.after_bulk_delete") method is a legacy event hook as of SQLAlchemy 2.0. The event **does not participate** in [2.0 style](https://docs.sqlalchemy.org/en/20/glossary.html#term-2.0-style) invocations using [delete()]($26c6626899a090f1.md#sqlalchemy.sql.expression.delete "sqlalchemy.sql.expression.delete") documented at [ORM UPDATE and DELETE with Custom WHERE Criteria]($8137f13cfe1f7fec.md#orm-queryguide-update-delete-where). For 2.0 style use, the [SessionEvents.do\_orm\_execute()](#sqlalchemy.orm.SessionEvents.do_orm_execute "sqlalchemy.orm.SessionEvents.do_orm_execute") hook will intercept these calls.
- Parameters:
**delete\_context** –
a “delete context” object which contains details about the update, including these attributes:
> - `session` - the [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") involved
>
> - `query` -the [Query]($3d0cc000ec6c7150.md#sqlalchemy.orm.Query "sqlalchemy.orm.Query") object that this update operation was called upon.
>
> - `result` the [CursorResult]($3743e3464fa80ce7.md#sqlalchemy.engine.CursorResult "sqlalchemy.engine.CursorResult") returned as a result of the bulk DELETE operation.
>
Changed in version 1.4: the update\_context no longer has a `QueryContext` object associated with it.
See also
[QueryEvents.before\_compile\_delete()](#sqlalchemy.orm.QueryEvents.before_compile_delete "sqlalchemy.orm.QueryEvents.before_compile_delete")
[SessionEvents.after\_bulk\_update()](#sqlalchemy.orm.SessionEvents.after_bulk_update "sqlalchemy.orm.SessionEvents.after_bulk_update")
method sqlalchemy.orm.SessionEvents.after_bulk_update(update_context: _O) → None
Event for after the legacy method has been called.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSessionClassOrObject, 'after_bulk_update')
def receive_after_bulk_update(update_context):
"listen for the 'after_bulk_update' event"
# ... (event handling logic) ...
# DEPRECATED calling style (pre-0.9, will be removed in a future release)
@event.listens_for(SomeSessionClassOrObject, '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 [SessionEvents.after\_bulk\_update()](#sqlalchemy.orm.SessionEvents.after_bulk_update "sqlalchemy.orm.SessionEvents.after_bulk_update") event now accepts the arguments [SessionEvents.after\_bulk\_update.update\_context](#sqlalchemy.orm.SessionEvents.after_bulk_update.params.update_context "sqlalchemy.orm.SessionEvents.after_bulk_update"). Support for listener functions which accept the previous argument signature(s) listed above as “deprecated” will be removed in a future release.
Legacy Feature
The [SessionEvents.after\_bulk\_update()](#sqlalchemy.orm.SessionEvents.after_bulk_update "sqlalchemy.orm.SessionEvents.after_bulk_update") method is a legacy event hook as of SQLAlchemy 2.0. The event **does not participate** in [2.0 style](https://docs.sqlalchemy.org/en/20/glossary.html#term-2.0-style) invocations using [update()]($26c6626899a090f1.md#sqlalchemy.sql.expression.update "sqlalchemy.sql.expression.update") documented at [ORM UPDATE and DELETE with Custom WHERE Criteria]($8137f13cfe1f7fec.md#orm-queryguide-update-delete-where). For 2.0 style use, the [SessionEvents.do\_orm\_execute()](#sqlalchemy.orm.SessionEvents.do_orm_execute "sqlalchemy.orm.SessionEvents.do_orm_execute") hook will intercept these calls.
- Parameters:
**update\_context** –
an “update context” object which contains details about the update, including these attributes:
> - `session` - the [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") involved
>
> - `query` -the [Query]($3d0cc000ec6c7150.md#sqlalchemy.orm.Query "sqlalchemy.orm.Query") object that this update operation was called upon.
>
> - `values` The “values” dictionary that was passed to [Query.update()]($3d0cc000ec6c7150.md#sqlalchemy.orm.Query.update "sqlalchemy.orm.Query.update").
>
> - `result` the [CursorResult]($3743e3464fa80ce7.md#sqlalchemy.engine.CursorResult "sqlalchemy.engine.CursorResult") returned as a result of the bulk UPDATE operation.
>
Changed in version 1.4: the update\_context no longer has a `QueryContext` object associated with it.
See also
[QueryEvents.before\_compile\_update()](#sqlalchemy.orm.QueryEvents.before_compile_update "sqlalchemy.orm.QueryEvents.before_compile_update")
[SessionEvents.after\_bulk\_delete()](#sqlalchemy.orm.SessionEvents.after_bulk_delete "sqlalchemy.orm.SessionEvents.after_bulk_delete")
method sqlalchemy.orm.SessionEvents.after_commit(session: ) → None
Execute after a commit has occurred.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSessionClassOrObject, 'after_commit')
def receive_after_commit(session):
"listen for the 'after_commit' event"
# ... (event handling logic) ...
```
Note
The [SessionEvents.after\_commit()](#sqlalchemy.orm.SessionEvents.after_commit "sqlalchemy.orm.SessionEvents.after_commit") hook is _not_ per-flush, that is, the [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") can emit SQL to the database many times within the scope of a transaction. For interception of these events, use the [SessionEvents.before\_flush()](#sqlalchemy.orm.SessionEvents.before_flush "sqlalchemy.orm.SessionEvents.before_flush"), [SessionEvents.after\_flush()](#sqlalchemy.orm.SessionEvents.after_flush "sqlalchemy.orm.SessionEvents.after_flush"), or [SessionEvents.after\_flush\_postexec()](#sqlalchemy.orm.SessionEvents.after_flush_postexec "sqlalchemy.orm.SessionEvents.after_flush_postexec") events.
Note
The [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") is not in an active transaction when the [SessionEvents.after\_commit()](#sqlalchemy.orm.SessionEvents.after_commit "sqlalchemy.orm.SessionEvents.after_commit") event is invoked, and therefore can not emit SQL. To emit SQL corresponding to every transaction, use the [SessionEvents.before\_commit()](#sqlalchemy.orm.SessionEvents.before_commit "sqlalchemy.orm.SessionEvents.before_commit") event.
- Parameters:
**session** – The target [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session").
See also
[SessionEvents.before\_commit()](#sqlalchemy.orm.SessionEvents.before_commit "sqlalchemy.orm.SessionEvents.before_commit")
[SessionEvents.after\_begin()](#sqlalchemy.orm.SessionEvents.after_begin "sqlalchemy.orm.SessionEvents.after_begin")
[SessionEvents.after\_transaction\_create()](#sqlalchemy.orm.SessionEvents.after_transaction_create "sqlalchemy.orm.SessionEvents.after_transaction_create")
[SessionEvents.after\_transaction\_end()](#sqlalchemy.orm.SessionEvents.after_transaction_end "sqlalchemy.orm.SessionEvents.after_transaction_end")
method sqlalchemy.orm.SessionEvents.after_flush(session: , flush_context: UOWTransaction) → None
Execute after flush has completed, but before commit has been called.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSessionClassOrObject, '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.
Warning
This event runs after the [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") has emitted SQL to modify the database, but **before** it has altered its internal state to reflect those changes, including that newly inserted objects are placed into the identity map. ORM operations emitted within this event such as loads of related items may produce new identity map entries that will immediately be replaced, sometimes causing confusing results. SQLAlchemy will emit a warning for this condition as of version 1.3.9.
- Parameters:
- **session** – The target [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session").
- **flush\_context** – Internal [UOWTransaction]($376e1901d3af4d61.md#sqlalchemy.orm.UOWTransaction "sqlalchemy.orm.UOWTransaction") object which handles the details of the flush.
See also
[SessionEvents.before\_flush()](#sqlalchemy.orm.SessionEvents.before_flush "sqlalchemy.orm.SessionEvents.before_flush")
[SessionEvents.after\_flush\_postexec()](#sqlalchemy.orm.SessionEvents.after_flush_postexec "sqlalchemy.orm.SessionEvents.after_flush_postexec")
[Persistence Events]($a1168341f79cb60a.md#session-persistence-events)
method after_flush_postexec(session: Session, flush_context: ) → None
Execute after flush has completed, and after the post-exec state occurs.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSessionClassOrObject, '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]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session").
- **flush\_context** – Internal [UOWTransaction]($376e1901d3af4d61.md#sqlalchemy.orm.UOWTransaction "sqlalchemy.orm.UOWTransaction") object which handles the details of the flush.
See also
[SessionEvents.before\_flush()](#sqlalchemy.orm.SessionEvents.before_flush "sqlalchemy.orm.SessionEvents.before_flush")
[SessionEvents.after\_flush()](#sqlalchemy.orm.SessionEvents.after_flush "sqlalchemy.orm.SessionEvents.after_flush")
[Persistence Events]($a1168341f79cb60a.md#session-persistence-events)
method sqlalchemy.orm.SessionEvents.after_rollback(session: ) → None
Execute after a real DBAPI rollback has occurred.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSessionClassOrObject, '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()]($694f628462946390.md#sqlalchemy.orm.Session.rollback "sqlalchemy.orm.Session.rollback") method is called, if the underlying DBAPI transaction has already been rolled back. In many cases, the [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") will not be in an “active” state during this event, as the current transaction is not valid. To acquire a [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") which is active after the outermost rollback has proceeded, use the [SessionEvents.after\_soft\_rollback()](#sqlalchemy.orm.SessionEvents.after_soft_rollback "sqlalchemy.orm.SessionEvents.after_soft_rollback") event, checking the [Session.is\_active]($694f628462946390.md#sqlalchemy.orm.Session.is_active "sqlalchemy.orm.Session.is_active") flag.
- Parameters:
**session** – The target [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session").
method sqlalchemy.orm.SessionEvents.after_soft_rollback(session: , previous_transaction: SessionTransaction) → None
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
@event.listens_for(SomeSessionClassOrObject, '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]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") can be used to invoke SQL and [Session.query()]($694f628462946390.md#sqlalchemy.orm.Session.query "sqlalchemy.orm.Session.query") operations after an outermost rollback by first checking the [Session.is\_active]($694f628462946390.md#sqlalchemy.orm.Session.is_active "sqlalchemy.orm.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]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session").
- **previous\_transaction** – The [SessionTransaction]($694f628462946390.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.SessionTransaction") transactional marker object which was just closed. The current [SessionTransaction]($694f628462946390.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.SessionTransaction") for the given [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") is available via the `Session.transaction` attribute.
method after_transaction_create(session: Session, transaction: ) → None
Execute when a new SessionTransaction is created.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSessionClassOrObject, 'after_transaction_create')
def receive_after_transaction_create(session, transaction):
"listen for the 'after_transaction_create' event"
# ... (event handling logic) ...
```
This event differs from [SessionEvents.after\_begin()](#sqlalchemy.orm.SessionEvents.after_begin "sqlalchemy.orm.SessionEvents.after_begin") in that it occurs for each [SessionTransaction]($694f628462946390.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.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 [SessionEvents.after\_transaction\_end()](#sqlalchemy.orm.SessionEvents.after_transaction_end "sqlalchemy.orm.SessionEvents.after_transaction_end") event (assuming normal operation of the [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session")).
- Parameters:
- **session** – the target [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session").
- **transaction** –
the target [SessionTransaction]($694f628462946390.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.SessionTransaction").
To detect if this is the outermost [SessionTransaction]($694f628462946390.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.SessionTransaction"), as opposed to a “subtransaction” or a SAVEPOINT, test that the [SessionTransaction.parent]($694f628462946390.md#sqlalchemy.orm.SessionTransaction.parent "sqlalchemy.orm.SessionTransaction.parent") attribute is `None`:
```
@event.listens_for(session, "after_transaction_create")
def after_transaction_create(session, transaction):
if transaction.parent is None:
# work with top-level transaction
```
To detect if the [SessionTransaction]($694f628462946390.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.SessionTransaction") is a SAVEPOINT, use the [SessionTransaction.nested]($694f628462946390.md#sqlalchemy.orm.SessionTransaction.nested "sqlalchemy.orm.SessionTransaction.nested") attribute:
```
@event.listens_for(session, "after_transaction_create")
def after_transaction_create(session, transaction):
if transaction.nested:
# work with SAVEPOINT transaction
```
See also
[SessionTransaction]($694f628462946390.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.SessionTransaction")
[SessionEvents.after\_transaction\_end()](#sqlalchemy.orm.SessionEvents.after_transaction_end "sqlalchemy.orm.SessionEvents.after_transaction_end")
method after_transaction_end(session: Session, transaction: ) → None
Execute when the span of a SessionTransaction ends.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSessionClassOrObject, 'after_transaction_end')
def receive_after_transaction_end(session, transaction):
"listen for the 'after_transaction_end' event"
# ... (event handling logic) ...
```
This event differs from [SessionEvents.after\_commit()](#sqlalchemy.orm.SessionEvents.after_commit "sqlalchemy.orm.SessionEvents.after_commit") in that it corresponds to all [SessionTransaction]($694f628462946390.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.SessionTransaction") objects in use, including those for nested transactions and subtransactions, and is always matched by a corresponding [SessionEvents.after\_transaction\_create()](#sqlalchemy.orm.SessionEvents.after_transaction_create "sqlalchemy.orm.SessionEvents.after_transaction_create") event.
- Parameters:
- **session** – the target [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session").
- **transaction** –
the target [SessionTransaction]($694f628462946390.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.SessionTransaction").
To detect if this is the outermost [SessionTransaction]($694f628462946390.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.SessionTransaction"), as opposed to a “subtransaction” or a SAVEPOINT, test that the [SessionTransaction.parent]($694f628462946390.md#sqlalchemy.orm.SessionTransaction.parent "sqlalchemy.orm.SessionTransaction.parent") attribute is `None`:
```
@event.listens_for(session, "after_transaction_create")
def after_transaction_end(session, transaction):
if transaction.parent is None:
# work with top-level transaction
```
To detect if the [SessionTransaction]($694f628462946390.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.SessionTransaction") is a SAVEPOINT, use the [SessionTransaction.nested]($694f628462946390.md#sqlalchemy.orm.SessionTransaction.nested "sqlalchemy.orm.SessionTransaction.nested") attribute:
```
@event.listens_for(session, "after_transaction_create")
def after_transaction_end(session, transaction):
if transaction.nested:
# work with SAVEPOINT transaction
```
See also
[SessionTransaction]($694f628462946390.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.SessionTransaction")
[SessionEvents.after\_transaction\_create()](#sqlalchemy.orm.SessionEvents.after_transaction_create "sqlalchemy.orm.SessionEvents.after_transaction_create")
method before_attach(session: Session, instance: _O) → None
Execute before an instance is attached to a session.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSessionClassOrObject, '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.
See also
[SessionEvents.after\_attach()](#sqlalchemy.orm.SessionEvents.after_attach "sqlalchemy.orm.SessionEvents.after_attach")
[Object Lifecycle Events]($a1168341f79cb60a.md#session-lifecycle-events)
method before_commit(session: Session) → None
Execute before commit is called.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSessionClassOrObject, 'before_commit')
def receive_before_commit(session):
"listen for the 'before_commit' event"
# ... (event handling logic) ...
```
Note
The [SessionEvents.before\_commit()](#sqlalchemy.orm.SessionEvents.before_commit "sqlalchemy.orm.SessionEvents.before_commit") hook is _not_ per-flush, that is, the [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") can emit SQL to the database many times within the scope of a transaction. For interception of these events, use the [SessionEvents.before\_flush()](#sqlalchemy.orm.SessionEvents.before_flush "sqlalchemy.orm.SessionEvents.before_flush"), [SessionEvents.after\_flush()](#sqlalchemy.orm.SessionEvents.after_flush "sqlalchemy.orm.SessionEvents.after_flush"), or [SessionEvents.after\_flush\_postexec()](#sqlalchemy.orm.SessionEvents.after_flush_postexec "sqlalchemy.orm.SessionEvents.after_flush_postexec") events.
- Parameters:
**session** – The target [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session").
See also
[SessionEvents.after\_commit()](#sqlalchemy.orm.SessionEvents.after_commit "sqlalchemy.orm.SessionEvents.after_commit")
[SessionEvents.after\_begin()](#sqlalchemy.orm.SessionEvents.after_begin "sqlalchemy.orm.SessionEvents.after_begin")
[SessionEvents.after\_transaction\_create()](#sqlalchemy.orm.SessionEvents.after_transaction_create "sqlalchemy.orm.SessionEvents.after_transaction_create")
[SessionEvents.after\_transaction\_end()](#sqlalchemy.orm.SessionEvents.after_transaction_end "sqlalchemy.orm.SessionEvents.after_transaction_end")
method before_flush(session: Session, flush_context: , instances: Optional[Sequence[_O]]) → None
Execute before flush process has started.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSessionClassOrObject, 'before_flush')
def receive_before_flush(session, flush_context, instances):
"listen for the 'before_flush' event"
# ... (event handling logic) ...
```
- Parameters:
- **session** – The target [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session").
- **flush\_context** – Internal [UOWTransaction]($376e1901d3af4d61.md#sqlalchemy.orm.UOWTransaction "sqlalchemy.orm.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()]($694f628462946390.md#sqlalchemy.orm.Session.flush "sqlalchemy.orm.Session.flush") method (note this usage is deprecated).
See also
[SessionEvents.after\_flush()](#sqlalchemy.orm.SessionEvents.after_flush "sqlalchemy.orm.SessionEvents.after_flush")
[SessionEvents.after\_flush\_postexec()](#sqlalchemy.orm.SessionEvents.after_flush_postexec "sqlalchemy.orm.SessionEvents.after_flush_postexec")
[Persistence Events]($a1168341f79cb60a.md#session-persistence-events)
method deleted_to_detached(session: Session, instance: _O) → None
Intercept the “deleted to detached” transition for a specific object.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSessionClassOrObject, 'deleted_to_detached')
def receive_deleted_to_detached(session, instance):
"listen for the 'deleted_to_detached' event"
# ... (event handling logic) ...
```
This event is invoked when a deleted object is evicted from the session. The typical case when this occurs is when the transaction for a [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") in which the object was deleted is committed; the object moves from the deleted state to the detached state.
It is also invoked for objects that were deleted in a flush when the [Session.expunge\_all()]($694f628462946390.md#sqlalchemy.orm.Session.expunge_all "sqlalchemy.orm.Session.expunge_all") or [Session.close()]($694f628462946390.md#sqlalchemy.orm.Session.close "sqlalchemy.orm.Session.close") events are called, as well as if the object is individually expunged from its deleted state via [Session.expunge()]($694f628462946390.md#sqlalchemy.orm.Session.expunge "sqlalchemy.orm.Session.expunge").
New in version 1.1.
See also
[Object Lifecycle Events]($a1168341f79cb60a.md#session-lifecycle-events)
method deleted_to_persistent(session: Session, instance: _O) → None
Intercept the “deleted to persistent” transition for a specific object.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSessionClassOrObject, 'deleted_to_persistent')
def receive_deleted_to_persistent(session, instance):
"listen for the 'deleted_to_persistent' event"
# ... (event handling logic) ...
```
This transition occurs only when an object that’s been deleted successfully in a flush is restored due to a call to [Session.rollback()]($694f628462946390.md#sqlalchemy.orm.Session.rollback "sqlalchemy.orm.Session.rollback"). The event is not called under any other circumstances.
New in version 1.1.
See also
[Object Lifecycle Events]($a1168341f79cb60a.md#session-lifecycle-events)
method detached_to_persistent(session: Session, instance: _O) → None
Intercept the “detached to persistent” transition for a specific object.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSessionClassOrObject, 'detached_to_persistent')
def receive_detached_to_persistent(session, instance):
"listen for the 'detached_to_persistent' event"
# ... (event handling logic) ...
```
This event is a specialization of the [SessionEvents.after\_attach()](#sqlalchemy.orm.SessionEvents.after_attach "sqlalchemy.orm.SessionEvents.after_attach") event which is only invoked for this specific transition. It is invoked typically during the [Session.add()]($694f628462946390.md#sqlalchemy.orm.Session.add "sqlalchemy.orm.Session.add") call, as well as during the [Session.delete()]($694f628462946390.md#sqlalchemy.orm.Session.delete "sqlalchemy.orm.Session.delete") call if the object was not previously associated with the [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") (note that an object marked as “deleted” remains in the “persistent” state until the flush proceeds).
Note
If the object becomes persistent as part of a call to [Session.delete()]($694f628462946390.md#sqlalchemy.orm.Session.delete "sqlalchemy.orm.Session.delete"), the object is **not** yet marked as deleted when this event is called. To detect deleted objects, check the `deleted` flag sent to the [SessionEvents.persistent\_to\_detached()](#sqlalchemy.orm.SessionEvents.persistent_to_detached "sqlalchemy.orm.SessionEvents.persistent_to_detached") to event after the flush proceeds, or check the [Session.deleted]($694f628462946390.md#sqlalchemy.orm.Session.deleted "sqlalchemy.orm.Session.deleted") collection within the [SessionEvents.before\_flush()](#sqlalchemy.orm.SessionEvents.before_flush "sqlalchemy.orm.SessionEvents.before_flush") event if deleted objects need to be intercepted before the flush.
- Parameters:
- **session** – target [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session")
- **instance** – the ORM-mapped instance being operated upon.
New in version 1.1.
See also
[Object Lifecycle Events]($a1168341f79cb60a.md#session-lifecycle-events)
attribute dispatch: _Dispatch[_ET] = <sqlalchemy.event.base.SessionEventsDispatch object>
reference back to the _Dispatch class.
Bidirectional against _Dispatch._events
method sqlalchemy.orm.SessionEvents.do_orm_execute(orm_execute_state: ) → None
Intercept statement executions that occur on behalf of an ORM Session object.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSessionClassOrObject, 'do_orm_execute')
def receive_do_orm_execute(orm_execute_state):
"listen for the 'do_orm_execute' event"
# ... (event handling logic) ...
```
This event is invoked for all top-level SQL statements invoked from the [Session.execute()]($694f628462946390.md#sqlalchemy.orm.Session.execute "sqlalchemy.orm.Session.execute") method, as well as related methods such as [Session.scalars()]($694f628462946390.md#sqlalchemy.orm.Session.scalars "sqlalchemy.orm.Session.scalars") and [Session.scalar()]($694f628462946390.md#sqlalchemy.orm.Session.scalar "sqlalchemy.orm.Session.scalar"). As of SQLAlchemy 1.4, all ORM queries emitted on behalf of a [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") will flow through this method, so this event hook provides the single point at which ORM queries of all types may be intercepted before they are invoked, and additionally to replace their execution with a different process.
Note
The [SessionEvents.do\_orm\_execute()](#sqlalchemy.orm.SessionEvents.do_orm_execute "sqlalchemy.orm.SessionEvents.do_orm_execute") event hook is triggered **for ORM statement executions only**, meaning those invoked via the [Session.execute()]($694f628462946390.md#sqlalchemy.orm.Session.execute "sqlalchemy.orm.Session.execute") and similar methods on the [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") object. It does **not** trigger for statements that are invoked by SQLAlchemy Core only, i.e. statements invoked directly using [Connection.execute()]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection.execute "sqlalchemy.engine.Connection.execute") or otherwise originating from an [Engine]($3743e3464fa80ce7.md#sqlalchemy.engine.Engine "sqlalchemy.engine.Engine") object without any [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") involved. To intercept **all** SQL executions regardless of whether the Core or ORM APIs are in use, see the event hooks at [ConnectionEvents]($03a0310aaf427e31.md#sqlalchemy.events.ConnectionEvents "sqlalchemy.events.ConnectionEvents"), such as [ConnectionEvents.before\_execute()]($03a0310aaf427e31.md#sqlalchemy.events.ConnectionEvents.before_execute "sqlalchemy.events.ConnectionEvents.before_execute") and [ConnectionEvents.before\_cursor\_execute()]($03a0310aaf427e31.md#sqlalchemy.events.ConnectionEvents.before_cursor_execute "sqlalchemy.events.ConnectionEvents.before_cursor_execute").
This event is a `do_` event, meaning it has the capability to replace the operation that the [Session.execute()]($694f628462946390.md#sqlalchemy.orm.Session.execute "sqlalchemy.orm.Session.execute") method normally performs. The intended use for this includes sharding and result-caching schemes which may seek to invoke the same statement across multiple database connections, returning a result that is merged from each of them, or which don’t invoke the statement at all, instead returning data from a cache.
The hook intends to replace the use of the `Query._execute_and_instances` method that could be subclassed prior to SQLAlchemy 1.4.
- Parameters:
**orm\_execute\_state** – an instance of [ORMExecuteState]($694f628462946390.md#sqlalchemy.orm.ORMExecuteState "sqlalchemy.orm.ORMExecuteState") which contains all information about the current execution, as well as helper functions used to derive other commonly required information. See that object for details.
See also
[Execute Events]($a1168341f79cb60a.md#session-execute-events) - top level documentation on how to use [SessionEvents.do\_orm\_execute()](#sqlalchemy.orm.SessionEvents.do_orm_execute "sqlalchemy.orm.SessionEvents.do_orm_execute")
[ORMExecuteState]($694f628462946390.md#sqlalchemy.orm.ORMExecuteState "sqlalchemy.orm.ORMExecuteState") - the object passed to the [SessionEvents.do\_orm\_execute()](#sqlalchemy.orm.SessionEvents.do_orm_execute "sqlalchemy.orm.SessionEvents.do_orm_execute") event which contains all information about the statement to be invoked. It also provides an interface to extend the current statement, options, and parameters as well as an option that allows programmatic invocation of the statement at any point.
[ORM Query Events]($898b211e0a16e865.md#examples-session-orm-events) - includes examples of using [SessionEvents.do\_orm\_execute()](#sqlalchemy.orm.SessionEvents.do_orm_execute "sqlalchemy.orm.SessionEvents.do_orm_execute")
[Dogpile Caching]($898b211e0a16e865.md#examples-caching) - an example of how to integrate Dogpile caching with the ORM [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") making use of the [SessionEvents.do\_orm\_execute()](#sqlalchemy.orm.SessionEvents.do_orm_execute "sqlalchemy.orm.SessionEvents.do_orm_execute") event hook.
[Horizontal Sharding]($898b211e0a16e865.md#examples-sharding) - the Horizontal Sharding example / extension relies upon the [SessionEvents.do\_orm\_execute()](#sqlalchemy.orm.SessionEvents.do_orm_execute "sqlalchemy.orm.SessionEvents.do_orm_execute") event hook to invoke a SQL statement on multiple backends and return a merged result.
New in version 1.4.
method loaded_as_persistent(session: Session, instance: _O) → None
Intercept the “loaded as persistent” transition for a specific object.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSessionClassOrObject, 'loaded_as_persistent')
def receive_loaded_as_persistent(session, instance):
"listen for the 'loaded_as_persistent' event"
# ... (event handling logic) ...
```
This event is invoked within the ORM loading process, and is invoked very similarly to the [InstanceEvents.load()](#sqlalchemy.orm.InstanceEvents.load "sqlalchemy.orm.InstanceEvents.load") event. However, the event here is linkable to a [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") class or instance, rather than to a mapper or class hierarchy, and integrates with the other session lifecycle events smoothly. The object is guaranteed to be present in the session’s identity map when this event is called.
Note
This event is invoked within the loader process before eager loaders may have been completed, and the object’s state may not be complete. Additionally, invoking row-level refresh operations on the object will place the object into a new loader context, interfering with the existing load context. See the note on [InstanceEvents.load()](#sqlalchemy.orm.InstanceEvents.load "sqlalchemy.orm.InstanceEvents.load") for background on making use of the [SessionEvents.restore\_load\_context](#sqlalchemy.orm.SessionEvents.params.restore_load_context "sqlalchemy.orm.SessionEvents") parameter, which works in the same manner as that of [InstanceEvents.restore\_load\_context](#sqlalchemy.orm.InstanceEvents.params.restore_load_context "sqlalchemy.orm.InstanceEvents"), in order to resolve this scenario.
- Parameters:
- **session** – target [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session")
- **instance** – the ORM-mapped instance being operated upon.
New in version 1.1.
See also
[Object Lifecycle Events]($a1168341f79cb60a.md#session-lifecycle-events)
method pending_to_persistent(session: Session, instance: _O) → None
Intercept the “pending to persistent”” transition for a specific object.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSessionClassOrObject, 'pending_to_persistent')
def receive_pending_to_persistent(session, instance):
"listen for the 'pending_to_persistent' event"
# ... (event handling logic) ...
```
This event is invoked within the flush process, and is similar to scanning the [Session.new]($694f628462946390.md#sqlalchemy.orm.Session.new "sqlalchemy.orm.Session.new") collection within the [SessionEvents.after\_flush()](#sqlalchemy.orm.SessionEvents.after_flush "sqlalchemy.orm.SessionEvents.after_flush") event. However, in this case the object has already been moved to the persistent state when the event is called.
- Parameters:
- **session** – target [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session")
- **instance** – the ORM-mapped instance being operated upon.
New in version 1.1.
See also
[Object Lifecycle Events]($a1168341f79cb60a.md#session-lifecycle-events)
method pending_to_transient(session: Session, instance: _O) → None
Intercept the “pending to transient” transition for a specific object.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSessionClassOrObject, 'pending_to_transient')
def receive_pending_to_transient(session, instance):
"listen for the 'pending_to_transient' event"
# ... (event handling logic) ...
```
This less common transition occurs when an pending object that has not been flushed is evicted from the session; this can occur when the [Session.rollback()]($694f628462946390.md#sqlalchemy.orm.Session.rollback "sqlalchemy.orm.Session.rollback") method rolls back the transaction, or when the [Session.expunge()]($694f628462946390.md#sqlalchemy.orm.Session.expunge "sqlalchemy.orm.Session.expunge") method is used.
- Parameters:
- **session** – target [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session")
- **instance** – the ORM-mapped instance being operated upon.
New in version 1.1.
See also
[Object Lifecycle Events]($a1168341f79cb60a.md#session-lifecycle-events)
method persistent_to_deleted(session: Session, instance: _O) → None
Intercept the “persistent to deleted” transition for a specific object.
Example argument forms:
``` from sqlalchemy import event
method persistent_to_detached(session: Session, instance: _O) → None
Intercept the “persistent to detached” transition for a specific object.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSessionClassOrObject, 'persistent_to_detached')
def receive_persistent_to_detached(session, instance):
"listen for the 'persistent_to_detached' event"
# ... (event handling logic) ...
```
This event is invoked when a persistent object is evicted from the session. There are many conditions that cause this to happen, including:
- using a method such as [Session.expunge()]($694f628462946390.md#sqlalchemy.orm.Session.expunge "sqlalchemy.orm.Session.expunge") or [Session.close()]($694f628462946390.md#sqlalchemy.orm.Session.close "sqlalchemy.orm.Session.close")
- Calling the [Session.rollback()]($694f628462946390.md#sqlalchemy.orm.Session.rollback "sqlalchemy.orm.Session.rollback") method, when the object was part of an INSERT statement for that session’s transaction
- Parameters:
- **session** – target [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session")
- **instance** – the ORM-mapped instance being operated upon.
- **deleted** – boolean. If True, indicates this object moved to the detached state because it was marked as deleted and flushed.
New in version 1.1.
See also
[Object Lifecycle Events]($a1168341f79cb60a.md#session-lifecycle-events)
method persistent_to_transient(session: Session, instance: _O) → None
Intercept the “persistent to transient” transition for a specific object.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeSessionClassOrObject, 'persistent_to_transient')
def receive_persistent_to_transient(session, instance):
"listen for the 'persistent_to_transient' event"
# ... (event handling logic) ...
```
This less common transition occurs when an pending object that has has been flushed is evicted from the session; this can occur when the [Session.rollback()]($694f628462946390.md#sqlalchemy.orm.Session.rollback "sqlalchemy.orm.Session.rollback") method rolls back the transaction.
- Parameters:
- **session** – target [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session")
- **instance** – the ORM-mapped instance being operated upon.
New in version 1.1.
See also
[Object Lifecycle Events]($a1168341f79cb60a.md#session-lifecycle-events)
method transient_to_pending(session: Session, instance: _O) → None
Intercept the “transient to pending” transition for a specific object.
Example argument forms:
@event.listens_for(SomeSessionClassOrObject, 'transient_to_pending')
def receive_transient_to_pending(session, instance):
"listen for the 'transient_to_pending' event"
# ... (event handling logic) ...
```
This event is a specialization of the [SessionEvents.after\_attach()](#sqlalchemy.orm.SessionEvents.after_attach "sqlalchemy.orm.SessionEvents.after_attach") event which is only invoked for this specific transition. It is invoked typically during the [Session.add()]($694f628462946390.md#sqlalchemy.orm.Session.add "sqlalchemy.orm.Session.add") call.
- Parameters:
- **session** – target [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session")
- **instance** – the ORM-mapped instance being operated upon.
New in version 1.1.
See also
[Object Lifecycle Events]($a1168341f79cb60a.md#session-lifecycle-events)
Mapper Events
Mapper event hooks encompass things that happen as related to individual or multiple Mapper objects, which are the central configurational object that maps a user-defined class to a object. Types of things which occur at the Mapper level include:
Per-object persistence operations - the most popular mapper hooks are the unit-of-work hooks such as , MapperEvents.after_update(), etc. These events are contrasted to the more coarse grained session-level events such as in that they occur within the flush process on a per-object basis; while finer grained activity on an object is more straightforward, availability of Session features is limited.
Mapper configuration events - the other major class of mapper hooks are those which occur as a class is mapped, as a mapper is finalized, and when sets of mappers are configured to refer to each other. These events include , MapperEvents.before_mapper_configured() and at the individual Mapper level, and and MapperEvents.after_configured() at the level of collections of objects.
Object Name | Description |
---|---|
Define events specific to mappings. |
class sqlalchemy.orm.MapperEvents
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.execute(
text("select my_special_function(%d)" % target.special_number)
).scalar()
# 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)objects
the Mapper class itself indicates listening for all mappers.
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 , and MapperEvents.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 and SessionEvents.after_flush() methods as more flexible and user-friendly hooks in which to apply additional database state during a flush.
When using , several modifiers are available to the 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 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.
Members
after_configured(), , after_insert(), , before_configured(), , before_insert(), , before_update(), , instrument_class(),
Class signature
class sqlalchemy.orm.MapperEvents (sqlalchemy.event.Events
)
method after_configured() → None
Called after a series of mappers have been configured.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeClass, 'after_configured')
def receive_after_configured():
"listen for the 'after_configured' event"
# ... (event handling logic) ...
```
The [MapperEvents.after\_configured()](#sqlalchemy.orm.MapperEvents.after_configured "sqlalchemy.orm.MapperEvents.after_configured") event is invoked each time the [configure\_mappers()]($3736cc9f0e9d089e.md#sqlalchemy.orm.configure_mappers "sqlalchemy.orm.configure_mappers") function is invoked, after the function has completed its work. [configure\_mappers()]($3736cc9f0e9d089e.md#sqlalchemy.orm.configure_mappers "sqlalchemy.orm.configure_mappers") is typically invoked automatically as mappings are first used, as well as each time new mappers have been made available and new mapper use is detected.
Contrast this event to the [MapperEvents.mapper\_configured()](#sqlalchemy.orm.MapperEvents.mapper_configured "sqlalchemy.orm.MapperEvents.mapper_configured") event, which is called on a per-mapper basis while the configuration operation proceeds; unlike that event, when this event is invoked, all cross-configurations (e.g. backrefs) will also have been made available for any mappers that were pending. Also contrast to [MapperEvents.before\_configured()](#sqlalchemy.orm.MapperEvents.before_configured "sqlalchemy.orm.MapperEvents.before_configured"), which is invoked before the series of mappers has been configured.
This event can **only** be applied to the [Mapper]($3736cc9f0e9d089e.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.Mapper") class, and not to individual mappings or mapped classes. It is only invoked for all mappings as a whole:
```
from sqlalchemy.orm import Mapper
@event.listens_for(Mapper, "after_configured")
def go():
# ...
```
Theoretically this event is called once per application, but is actually called any time new mappers have been affected by a [configure\_mappers()]($3736cc9f0e9d089e.md#sqlalchemy.orm.configure_mappers "sqlalchemy.orm.configure_mappers") call. If new mappings are constructed after existing ones have already been used, this event will likely be called again. To ensure that a particular event is only called once and no further, the `once=True` argument (new in 0.9.4) can be applied:
```
from sqlalchemy.orm import mapper
@event.listens_for(mapper, "after_configured", once=True)
def go():
# ...
```
See also
[MapperEvents.before\_mapper\_configured()](#sqlalchemy.orm.MapperEvents.before_mapper_configured "sqlalchemy.orm.MapperEvents.before_mapper_configured")
[MapperEvents.mapper\_configured()](#sqlalchemy.orm.MapperEvents.mapper_configured "sqlalchemy.orm.MapperEvents.mapper_configured")
[MapperEvents.before\_configured()](#sqlalchemy.orm.MapperEvents.before_configured "sqlalchemy.orm.MapperEvents.before_configured")
method sqlalchemy.orm.MapperEvents.after_delete(mapper: [_O], connection: Connection, target: _O) → None
Receive an object instance after a DELETE statement has been emitted corresponding to that instance.
Example argument forms:
``` from sqlalchemy import event
@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 only allow **very limited operations**, on attributes local to the row being operated upon only, as well as allowing any SQL to be emitted on the given [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection"). **Please read fully** the notes at [Mapper-level Events]($a1168341f79cb60a.md#session-persistence-mapper) for guidelines on using these methods; generally, the [SessionEvents.before\_flush()](#sqlalchemy.orm.SessionEvents.before_flush "sqlalchemy.orm.SessionEvents.before_flush") method should be preferred for general on-flush changes.
- Parameters:
- **mapper** – the [Mapper]($3736cc9f0e9d089e.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.Mapper") which is the target of this event.
- **connection** – the [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.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]($376e1901d3af4d61.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
Returns:
No return value is supported by this event.
See also
[Persistence Events]($a1168341f79cb60a.md#session-persistence-events)
method after_insert(mapper: Mapper[_O], connection: , target: _O) → None
Receive an object instance after an INSERT statement is emitted corresponding to that instance.
Example argument forms:
``` from sqlalchemy import event
@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]($3736cc9f0e9d089e.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.Mapper") object 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 only allow **very limited operations**, on attributes local to the row being operated upon only, as well as allowing any SQL to be emitted on the given [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection"). **Please read fully** the notes at [Mapper-level Events]($a1168341f79cb60a.md#session-persistence-mapper) for guidelines on using these methods; generally, the [SessionEvents.before\_flush()](#sqlalchemy.orm.SessionEvents.before_flush "sqlalchemy.orm.SessionEvents.before_flush") method should be preferred for general on-flush changes.
- Parameters:
- **mapper** – the [Mapper]($3736cc9f0e9d089e.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.Mapper") which is the target of this event.
- **connection** – the [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.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]($376e1901d3af4d61.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
Returns:
No return value is supported by this event.
See also
[Persistence Events]($a1168341f79cb60a.md#session-persistence-events)
method sqlalchemy.orm.MapperEvents.after_update(mapper: [_O], connection: Connection, target: _O) → None
Receive an object instance after an UPDATE statement is emitted corresponding to that instance.
Example argument forms:
``` from sqlalchemy import event
@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 [MapperEvents.after\_update()](#sqlalchemy.orm.MapperEvents.after_update "sqlalchemy.orm.MapperEvents.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]($3736cc9f0e9d089e.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.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 only allow **very limited operations**, on attributes local to the row being operated upon only, as well as allowing any SQL to be emitted on the given [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection"). **Please read fully** the notes at [Mapper-level Events]($a1168341f79cb60a.md#session-persistence-mapper) for guidelines on using these methods; generally, the [SessionEvents.before\_flush()](#sqlalchemy.orm.SessionEvents.before_flush "sqlalchemy.orm.SessionEvents.before_flush") method should be preferred for general on-flush changes.
- Parameters:
- **mapper** – the [Mapper]($3736cc9f0e9d089e.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.Mapper") which is the target of this event.
- **connection** – the [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.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]($376e1901d3af4d61.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
Returns:
No return value is supported by this event.
See also
[Persistence Events]($a1168341f79cb60a.md#session-persistence-events)
method before_configured() → None
Called before a series of mappers have been configured.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeClass, 'before_configured')
def receive_before_configured():
"listen for the 'before_configured' event"
# ... (event handling logic) ...
```
The [MapperEvents.before\_configured()](#sqlalchemy.orm.MapperEvents.before_configured "sqlalchemy.orm.MapperEvents.before_configured") event is invoked each time the [configure\_mappers()]($3736cc9f0e9d089e.md#sqlalchemy.orm.configure_mappers "sqlalchemy.orm.configure_mappers") function is invoked, before the function has done any of its work. [configure\_mappers()]($3736cc9f0e9d089e.md#sqlalchemy.orm.configure_mappers "sqlalchemy.orm.configure_mappers") is typically invoked automatically as mappings are first used, as well as each time new mappers have been made available and new mapper use is detected.
This event can **only** be applied to the [Mapper]($3736cc9f0e9d089e.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.Mapper") class, and not to individual mappings or mapped classes. It is only invoked for all mappings as a whole:
```
from sqlalchemy.orm import Mapper
@event.listens_for(Mapper, "before_configured")
def go():
# ...
```
Contrast this event to [MapperEvents.after\_configured()](#sqlalchemy.orm.MapperEvents.after_configured "sqlalchemy.orm.MapperEvents.after_configured"), which is invoked after the series of mappers has been configured, as well as [MapperEvents.before\_mapper\_configured()](#sqlalchemy.orm.MapperEvents.before_mapper_configured "sqlalchemy.orm.MapperEvents.before_mapper_configured") and [MapperEvents.mapper\_configured()](#sqlalchemy.orm.MapperEvents.mapper_configured "sqlalchemy.orm.MapperEvents.mapper_configured"), which are both invoked on a per-mapper basis.
Theoretically this event is called once per application, but is actually called any time new mappers are to be affected by a [configure\_mappers()]($3736cc9f0e9d089e.md#sqlalchemy.orm.configure_mappers "sqlalchemy.orm.configure_mappers") call. If new mappings are constructed after existing ones have already been used, this event will likely be called again. To ensure that a particular event is only called once and no further, the `once=True` argument (new in 0.9.4) can be applied:
```
from sqlalchemy.orm import mapper
@event.listens_for(mapper, "before_configured", once=True)
def go():
# ...
```
New in version 0.9.3.
See also
[MapperEvents.before\_mapper\_configured()](#sqlalchemy.orm.MapperEvents.before_mapper_configured "sqlalchemy.orm.MapperEvents.before_mapper_configured")
[MapperEvents.mapper\_configured()](#sqlalchemy.orm.MapperEvents.mapper_configured "sqlalchemy.orm.MapperEvents.mapper_configured")
[MapperEvents.after\_configured()](#sqlalchemy.orm.MapperEvents.after_configured "sqlalchemy.orm.MapperEvents.after_configured")
method sqlalchemy.orm.MapperEvents.before_delete(mapper: [_O], connection: Connection, target: _O) → None
Receive an object instance before a DELETE statement is emitted corresponding to that instance.
Example argument forms:
``` from sqlalchemy import event
@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 only allow **very limited operations**, on attributes local to the row being operated upon only, as well as allowing any SQL to be emitted on the given [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection"). **Please read fully** the notes at [Mapper-level Events]($a1168341f79cb60a.md#session-persistence-mapper) for guidelines on using these methods; generally, the [SessionEvents.before\_flush()](#sqlalchemy.orm.SessionEvents.before_flush "sqlalchemy.orm.SessionEvents.before_flush") method should be preferred for general on-flush changes.
- Parameters:
- **mapper** – the [Mapper]($3736cc9f0e9d089e.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.Mapper") which is the target of this event.
- **connection** – the [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.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]($376e1901d3af4d61.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
Returns:
No return value is supported by this event.
See also
[Persistence Events]($a1168341f79cb60a.md#session-persistence-events)
method before_insert(mapper: Mapper[_O], connection: , target: _O) → None
Receive an object instance before an INSERT statement is emitted corresponding to that instance.
Example argument forms:
``` from sqlalchemy import event
@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]($3736cc9f0e9d089e.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.Mapper") object 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 only allow **very limited operations**, on attributes local to the row being operated upon only, as well as allowing any SQL to be emitted on the given [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection"). **Please read fully** the notes at [Mapper-level Events]($a1168341f79cb60a.md#session-persistence-mapper) for guidelines on using these methods; generally, the [SessionEvents.before\_flush()](#sqlalchemy.orm.SessionEvents.before_flush "sqlalchemy.orm.SessionEvents.before_flush") method should be preferred for general on-flush changes.
- Parameters:
- **mapper** – the [Mapper]($3736cc9f0e9d089e.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.Mapper") which is the target of this event.
- **connection** – the [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.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]($376e1901d3af4d61.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
Returns:
No return value is supported by this event.
See also
[Persistence Events]($a1168341f79cb60a.md#session-persistence-events)
method sqlalchemy.orm.MapperEvents.before_mapper_configured(mapper: [_O], class\: Type[_O]_) → None
Called right before a specific mapper is to be configured.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeClass, 'before_mapper_configured')
def receive_before_mapper_configured(mapper, class_):
"listen for the 'before_mapper_configured' event"
# ... (event handling logic) ...
```
This event is intended to allow a specific mapper to be skipped during the configure step, by returning the `interfaces.EXT_SKIP` symbol which indicates to the [configure\_mappers()]($3736cc9f0e9d089e.md#sqlalchemy.orm.configure_mappers "sqlalchemy.orm.configure_mappers") call that this particular mapper (or hierarchy of mappers, if `propagate=True` is used) should be skipped in the current configuration run. When one or more mappers are skipped, the he “new mappers” flag will remain set, meaning the [configure\_mappers()]($3736cc9f0e9d089e.md#sqlalchemy.orm.configure_mappers "sqlalchemy.orm.configure_mappers") function will continue to be called when mappers are used, to continue to try to configure all available mappers.
In comparison to the other configure-level events, [MapperEvents.before\_configured()](#sqlalchemy.orm.MapperEvents.before_configured "sqlalchemy.orm.MapperEvents.before_configured"), [MapperEvents.after\_configured()](#sqlalchemy.orm.MapperEvents.after_configured "sqlalchemy.orm.MapperEvents.after_configured"), and [MapperEvents.mapper\_configured()](#sqlalchemy.orm.MapperEvents.mapper_configured "sqlalchemy.orm.MapperEvents.mapper_configured"), the :meth;\`.MapperEvents.before\_mapper\_configured\` event provides for a meaningful return value when it is registered with the `retval=True` parameter.
New in version 1.3.
e.g.:
```
from sqlalchemy.orm import EXT_SKIP
Base = declarative_base()
DontConfigureBase = declarative_base()
@event.listens_for(
DontConfigureBase,
"before_mapper_configured", retval=True, propagate=True)
def dont_configure(mapper, cls):
return EXT_SKIP
```
See also
[MapperEvents.before\_configured()](#sqlalchemy.orm.MapperEvents.before_configured "sqlalchemy.orm.MapperEvents.before_configured")
[MapperEvents.after\_configured()](#sqlalchemy.orm.MapperEvents.after_configured "sqlalchemy.orm.MapperEvents.after_configured")
[MapperEvents.mapper\_configured()](#sqlalchemy.orm.MapperEvents.mapper_configured "sqlalchemy.orm.MapperEvents.mapper_configured")
method sqlalchemy.orm.MapperEvents.before_update(mapper: [_O], connection: Connection, target: _O) → None
Receive an object instance before an UPDATE statement is emitted corresponding to that instance.
Example argument forms:
``` from sqlalchemy import event
@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 [MapperEvents.before\_update()](#sqlalchemy.orm.MapperEvents.before_update "sqlalchemy.orm.MapperEvents.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]($3736cc9f0e9d089e.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.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 only allow **very limited operations**, on attributes local to the row being operated upon only, as well as allowing any SQL to be emitted on the given [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection"). **Please read fully** the notes at [Mapper-level Events]($a1168341f79cb60a.md#session-persistence-mapper) for guidelines on using these methods; generally, the [SessionEvents.before\_flush()](#sqlalchemy.orm.SessionEvents.before_flush "sqlalchemy.orm.SessionEvents.before_flush") method should be preferred for general on-flush changes.
- Parameters:
- **mapper** – the [Mapper]($3736cc9f0e9d089e.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.Mapper") which is the target of this event.
- **connection** – the [Connection]($3743e3464fa80ce7.md#sqlalchemy.engine.Connection "sqlalchemy.engine.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]($376e1901d3af4d61.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
Returns:
No return value is supported by this event.
See also
[Persistence Events]($a1168341f79cb60a.md#session-persistence-events)
attribute dispatch: _Dispatch[_ET] = <sqlalchemy.event.base.MapperEventsDispatch object>
reference back to the _Dispatch class.
Bidirectional against _Dispatch._events
method sqlalchemy.orm.MapperEvents.instrument_class(mapper: [_O], class\: Type[_O]_) → None
Receive a class when the mapper is first constructed, before instrumentation is applied to the mapped class.
Example argument forms:
``` from sqlalchemy import event
@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]($3736cc9f0e9d089e.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.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]($3736cc9f0e9d089e.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.Mapper") which is the target of this event.
- **class\_** – the mapped class.
method sqlalchemy.orm.MapperEvents.mapper_configured(mapper: [_O], class\: Type[_O]_) → None
Called when a specific mapper has completed its own configuration within the scope of the configure_mappers() call.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeClass, 'mapper_configured')
def receive_mapper_configured(mapper, class_):
"listen for the 'mapper_configured' event"
# ... (event handling logic) ...
```
The [MapperEvents.mapper\_configured()](#sqlalchemy.orm.MapperEvents.mapper_configured "sqlalchemy.orm.MapperEvents.mapper_configured") event is invoked for each mapper that is encountered when the [configure\_mappers()]($3736cc9f0e9d089e.md#sqlalchemy.orm.configure_mappers "sqlalchemy.orm.configure_mappers") function proceeds through the current list of not-yet-configured mappers. [configure\_mappers()]($3736cc9f0e9d089e.md#sqlalchemy.orm.configure_mappers "sqlalchemy.orm.configure_mappers") is typically invoked automatically as mappings are first used, as well as each time new mappers have been made available and new mapper use is detected.
When the event is called, the mapper should be in its final state, but **not including backrefs** that may be invoked from other mappers; they might still be pending within the configuration operation. Bidirectional relationships that are instead configured via the [relationship.back\_populates]($d1a2bc9407b46431.md#sqlalchemy.orm.relationship.params.back_populates "sqlalchemy.orm.relationship") argument _will_ be fully available, since this style of relationship does not rely upon other possibly-not-configured mappers to know that they exist.
For an event that is guaranteed to have **all** mappers ready to go including backrefs that are defined only on other mappings, use the [MapperEvents.after\_configured()](#sqlalchemy.orm.MapperEvents.after_configured "sqlalchemy.orm.MapperEvents.after_configured") event; this event invokes only after all known mappings have been fully configured.
The [MapperEvents.mapper\_configured()](#sqlalchemy.orm.MapperEvents.mapper_configured "sqlalchemy.orm.MapperEvents.mapper_configured") event, unlike [MapperEvents.before\_configured()](#sqlalchemy.orm.MapperEvents.before_configured "sqlalchemy.orm.MapperEvents.before_configured") or [MapperEvents.after\_configured()](#sqlalchemy.orm.MapperEvents.after_configured "sqlalchemy.orm.MapperEvents.after_configured"), is called for each mapper/class individually, and the mapper is passed to the event itself. It also is called exactly once for a particular mapper. The event is therefore useful for configurational steps that benefit from being invoked just once on a specific mapper basis, which don’t require that “backref” configurations are necessarily ready yet.
- Parameters:
- **mapper** – the [Mapper]($3736cc9f0e9d089e.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.Mapper") which is the target of this event.
- **class\_** – the mapped class.
See also
[MapperEvents.before\_configured()](#sqlalchemy.orm.MapperEvents.before_configured "sqlalchemy.orm.MapperEvents.before_configured")
[MapperEvents.after\_configured()](#sqlalchemy.orm.MapperEvents.after_configured "sqlalchemy.orm.MapperEvents.after_configured")
[MapperEvents.before\_mapper\_configured()](#sqlalchemy.orm.MapperEvents.before_mapper_configured "sqlalchemy.orm.MapperEvents.before_mapper_configured")
Instance events are focused on the construction of ORM mapped instances, including when they are instantiated as transient objects, when they are loaded from the database and become objects, as well as when database refresh or expiration operations occur on the object.
class sqlalchemy.orm.InstanceEvents
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 class itself indicates listening for all mappers.
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 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.
restore_load_context=False –
Applies to the and InstanceEvents.refresh() events. Restores the loader context of the object when the event hook is complete, so that ongoing eager load operations continue to target the object appropriately. A warning is emitted if the object is moved to a new loader context from within one of these events if this flag is not set.
New in version 1.3.14.
Members
, expire(), , init(), , load(), , refresh(), , unpickle()
Class signature
class (sqlalchemy.event.Events
)
attribute sqlalchemy.orm.InstanceEvents.dispatch: _Dispatch[_ET] = <sqlalchemy.event.base.InstanceEventsDispatch object>
reference back to the _Dispatch class.
Bidirectional against _Dispatch._events
method expire(target: _O, attrs: Optional[Iterable[str]]) → None
Receive an object instance after its attributes or some subset have been expired.
Example argument forms:
``` from sqlalchemy import event
@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]($376e1901d3af4d61.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
- **attrs** – sequence of attribute names which were expired, or None if all attributes were expired.
method sqlalchemy.orm.InstanceEvents.first_init(manager: [_O], cls: Type[_O]) → None
Called when the first instance of a particular mapping is called.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeClass, 'first_init')
def receive_first_init(manager, cls):
"listen for the 'first_init' event"
# ... (event handling logic) ...
```
This event is called when the `__init__` method of a class is called the first time for that particular class. The event invokes before `__init__` actually proceeds as well as before the [InstanceEvents.init()](#sqlalchemy.orm.InstanceEvents.init "sqlalchemy.orm.InstanceEvents.init") event is invoked.
method sqlalchemy.orm.InstanceEvents.init(target: _O, args: Any, kwargs: Any) → None
Receive an instance when its constructor is called.
Example argument forms:
``` from sqlalchemy import event
@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, in conjunction with the object’s constructor, e.g. its `__init__` method. It is not called when an object is loaded from the database; see the [InstanceEvents.load()](#sqlalchemy.orm.InstanceEvents.load "sqlalchemy.orm.InstanceEvents.load") event in order to intercept a database load.
The event is called before the actual `__init__` constructor of the object is called. The `kwargs` dictionary may be modified in-place in order to affect what is passed to `__init__`.
- Parameters:
- **target** – the mapped instance. If the event is configured with `raw=True`, this will instead be the [InstanceState]($376e1901d3af4d61.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
- **args** – positional arguments passed to the `__init__` method. This is passed as a tuple and is currently immutable.
- **kwargs** – keyword arguments passed to the `__init__` method. This structure _can_ be altered in place.
See also
[InstanceEvents.init\_failure()](#sqlalchemy.orm.InstanceEvents.init_failure "sqlalchemy.orm.InstanceEvents.init_failure")
[InstanceEvents.load()](#sqlalchemy.orm.InstanceEvents.load "sqlalchemy.orm.InstanceEvents.load")
method init_failure(target: _O, args: Any, kwargs: Any) → None
Receive an instance when its constructor has been called, and raised an exception.
Example argument forms:
``` from sqlalchemy import event
@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, in conjunction with the object’s constructor, e.g. its `__init__` method. It is not called when an object is loaded from the database.
The event is invoked after an exception raised by the `__init__` method is caught. After the event is invoked, the original exception is re-raised outwards, so that the construction of the object still raises an exception. The actual exception and stack trace raised should be present in `sys.exc_info()`.
- Parameters:
- **target** – the mapped instance. If the event is configured with `raw=True`, this will instead be the [InstanceState]($376e1901d3af4d61.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
- **args** – positional arguments that were passed to the `__init__` method.
- **kwargs** – keyword arguments that were passed to the `__init__` method.
See also
[InstanceEvents.init()](#sqlalchemy.orm.InstanceEvents.init "sqlalchemy.orm.InstanceEvents.init")
[InstanceEvents.load()](#sqlalchemy.orm.InstanceEvents.load "sqlalchemy.orm.InstanceEvents.load")
method sqlalchemy.orm.InstanceEvents.load(target: _O, context: ) → None
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
@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.
Warning
During a result-row load, this event is invoked when the first row received for this instance is processed. When using eager loading with collection-oriented attributes, the additional rows that are to be loaded / processed in order to load subsequent collection items have not occurred yet. This has the effect both that collections will not be fully loaded, as well as that if an operation occurs within this event handler that emits another database load operation for the object, the “loading context” for the object can change and interfere with the existing eager loaders still in progress.
Examples of what can cause the “loading context” to change within the event handler include, but are not necessarily limited to:
- accessing deferred attributes that weren’t part of the row, will trigger an “undefer” operation and refresh the object
- accessing attributes on a joined-inheritance subclass that weren’t part of the row, will trigger a refresh operation.
As of SQLAlchemy 1.3.14, a warning is emitted when this occurs. The [InstanceEvents.restore\_load\_context](#sqlalchemy.orm.InstanceEvents.params.restore_load_context "sqlalchemy.orm.InstanceEvents") option may be used on the event to prevent this warning; this will ensure that the existing loading context is maintained for the object after the event is called:
```
@event.listens_for(
SomeClass, "load", restore_load_context=True)
def on_load(instance, context):
instance.some_unloaded_attribute
```
Changed in version 1.3.14: Added [InstanceEvents.restore\_load\_context](#sqlalchemy.orm.InstanceEvents.params.restore_load_context "sqlalchemy.orm.InstanceEvents") and [SessionEvents.restore\_load\_context](#sqlalchemy.orm.SessionEvents.params.restore_load_context "sqlalchemy.orm.SessionEvents") flags which apply to “on load” events, which will ensure that the loading context for an object is restored when the event hook is complete; a warning is emitted if the load context of the object changes without this flag being set.
The [InstanceEvents.load()](#sqlalchemy.orm.InstanceEvents.load "sqlalchemy.orm.InstanceEvents.load") event is also available in a class-method decorator format called [reconstructor()]($3736cc9f0e9d089e.md#sqlalchemy.orm.reconstructor "sqlalchemy.orm.reconstructor").
- Parameters:
- **target** – the mapped instance. If the event is configured with `raw=True`, this will instead be the [InstanceState]($376e1901d3af4d61.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
- **context** – the [QueryContext]($376e1901d3af4d61.md#sqlalchemy.orm.QueryContext "sqlalchemy.orm.QueryContext") corresponding to the current [Query]($3d0cc000ec6c7150.md#sqlalchemy.orm.Query "sqlalchemy.orm.Query") in progress. This argument may be `None` if the load does not correspond to a [Query]($3d0cc000ec6c7150.md#sqlalchemy.orm.Query "sqlalchemy.orm.Query"), such as during [Session.merge()]($694f628462946390.md#sqlalchemy.orm.Session.merge "sqlalchemy.orm.Session.merge").
See also
[InstanceEvents.init()](#sqlalchemy.orm.InstanceEvents.init "sqlalchemy.orm.InstanceEvents.init")
[InstanceEvents.refresh()](#sqlalchemy.orm.InstanceEvents.refresh "sqlalchemy.orm.InstanceEvents.refresh")
[SessionEvents.loaded\_as\_persistent()](#sqlalchemy.orm.SessionEvents.loaded_as_persistent "sqlalchemy.orm.SessionEvents.loaded_as_persistent")
[Constructors and Object Initialization](https://docs.sqlalchemy.org/en/20/orm/constructors.html#mapping-constructors)
method sqlalchemy.orm.InstanceEvents.pickle(target: _O, state_dict: _InstanceDict) → None
Receive an object instance when its associated state is being pickled.
Example argument forms:
``` from sqlalchemy import event
method refresh(target: _O, context: QueryContext, attrs: Optional[Iterable[str]]) → None
Receive an object instance after one or more attributes have been refreshed from a query.
``` from sqlalchemy import event
@event.listens_for(SomeClass, 'refresh')
def receive_refresh(target, context, attrs):
"listen for the 'refresh' event"
```
Contrast this to the [InstanceEvents.load()](#sqlalchemy.orm.InstanceEvents.load "sqlalchemy.orm.InstanceEvents.load") method, which is invoked when the object is first loaded from a query.
Note
This event is invoked within the loader process before eager loaders may have been completed, and the object’s state may not be complete. Additionally, invoking row-level refresh operations on the object will place the object into a new loader context, interfering with the existing load context. See the note on [InstanceEvents.load()](#sqlalchemy.orm.InstanceEvents.load "sqlalchemy.orm.InstanceEvents.load") for background on making use of the [InstanceEvents.restore\_load\_context](#sqlalchemy.orm.InstanceEvents.params.restore_load_context "sqlalchemy.orm.InstanceEvents") parameter, in order to resolve this scenario.
- Parameters:
- **target** – the mapped instance. If the event is configured with `raw=True`, this will instead be the [InstanceState]($376e1901d3af4d61.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
- **context** – the [QueryContext]($376e1901d3af4d61.md#sqlalchemy.orm.QueryContext "sqlalchemy.orm.QueryContext") corresponding to the current [Query]($3d0cc000ec6c7150.md#sqlalchemy.orm.Query "sqlalchemy.orm.Query") in progress.
- **attrs** – sequence of attribute names which were populated, or None if all column-mapped, non-deferred attributes were populated.
See also
[InstanceEvents.load()](#sqlalchemy.orm.InstanceEvents.load "sqlalchemy.orm.InstanceEvents.load")
method refresh_flush(target: _O, flush_context: UOWTransaction, attrs: Optional[Iterable[str]]) → None
Receive an object instance after one or more attributes that contain a column-level default or onupdate handler have been refreshed during persistence of the object’s state.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeClass, 'refresh_flush')
def receive_refresh_flush(target, flush_context, attrs):
"listen for the 'refresh_flush' event"
# ... (event handling logic) ...
```
This event is the same as [InstanceEvents.refresh()](#sqlalchemy.orm.InstanceEvents.refresh "sqlalchemy.orm.InstanceEvents.refresh") except it is invoked within the unit of work flush process, and includes only non-primary-key columns that have column level default or onupdate handlers, including Python callables as well as server side defaults and triggers which may be fetched via the RETURNING clause.
Note
While the [InstanceEvents.refresh\_flush()](#sqlalchemy.orm.InstanceEvents.refresh_flush "sqlalchemy.orm.InstanceEvents.refresh_flush") event is triggered for an object that was INSERTed as well as for an object that was UPDATEd, the event is geared primarily towards the UPDATE process; it is mostly an internal artifact that INSERT actions can also trigger this event, and note that **primary key columns for an INSERTed row are explicitly omitted** from this event. In order to intercept the newly INSERTed state of an object, the [SessionEvents.pending\_to\_persistent()](#sqlalchemy.orm.SessionEvents.pending_to_persistent "sqlalchemy.orm.SessionEvents.pending_to_persistent") and [MapperEvents.after\_insert()](#sqlalchemy.orm.MapperEvents.after_insert "sqlalchemy.orm.MapperEvents.after_insert") are better choices.
New in version 1.0.5.
- Parameters:
- **target** – the mapped instance. If the event is configured with `raw=True`, this will instead be the [InstanceState]($376e1901d3af4d61.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
- **flush\_context** – Internal [UOWTransaction]($376e1901d3af4d61.md#sqlalchemy.orm.UOWTransaction "sqlalchemy.orm.UOWTransaction") object which handles the details of the flush.
- **attrs** – sequence of attribute names which were populated.
See also
[Fetching Server-Generated Defaults]($47efe01e33821e5c.md#orm-server-defaults)
[Column INSERT/UPDATE Defaults]($6bf23ed88b114c55.md)
method unpickle(target: _O, state_dict: _InstanceDict) → None
Receive an object instance after its associated state has been unpickled.
Example argument forms:
``` from sqlalchemy import event
@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]($376e1901d3af4d61.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
- **state\_dict** – the dictionary sent to `__setstate__`, containing the state dictionary which was pickled.
Attribute Events
Attribute events are triggered as things occur on individual attributes of ORM mapped objects. These events form the basis for things like as well as backref handlers.
See also
Object Name | Description |
---|---|
Define events for object attributes. |
class sqlalchemy.orm.AttributeEvents
Define events for object attributes.
These are typically defined on the class-bound descriptor for the target class.
For example, to register a listener that will receive the event:
from sqlalchemy import event
@event.listens_for(MyClass.collection, 'append', propagate=True)
def my_append_listener(target, value, initiator):
print("received append event for target: %s" % target)
Listeners have the option to return a possibly modified version of the value, when the AttributeEvents.retval flag is passed to or listens_for(), such as below, illustrated using the event:
def validate_phone(target, value, oldvalue, initiator):
"Strip non-numeric characters from a phone number"
return re.sub(r'\D', '', 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.
The AttributeEvents.propagate flag is also important when applying listeners to mapped classes that also have mapped subclasses, as when using mapper inheritance patterns:
@event.listens_for(MySuperClass.attr, 'set', propagate=True)
def receive_set(target, value, initiator):
print("value set: %s" % target)
The full list of modifiers available to the and listens_for() functions are below.
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 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 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.
Members
append(), , bulk_replace(), , dispose_collection(), , init_scalar(), , remove(),
Class signature
class sqlalchemy.orm.AttributeEvents (sqlalchemy.event.Events
)
method append(target: _O, value: _T, initiator: Event, *, key: EventConstants = EventConstants.NO_KEY) → Optional[_T]
Receive a collection append event.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeClass.some_attribute, 'append')
def receive_append(target, value, initiator):
"listen for the 'append' event"
# ... (event handling logic) ...
```
The append event is invoked for each element as it is appended to the collection. This occurs for single-item appends as well as for a “bulk replace” operation.
- Parameters:
- **target** – the object instance receiving the event. If the listener is registered with `raw=True`, this will be the [InstanceState]($376e1901d3af4d61.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.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 `Event` representing the initiation of the event. May be modified from its original value by backref handlers in order to control chained event propagation, as well as be inspected for information about the source of the event.
- **key** –
When the event is established using the [AttributeEvents.include\_key](#sqlalchemy.orm.AttributeEvents.params.include_key "sqlalchemy.orm.AttributeEvents") parameter set to True, this will be the key used in the operation, such as `collection[some_key_or_index] = value`. The parameter is not passed to the event at all if the the [AttributeEvents.include\_key](#sqlalchemy.orm.AttributeEvents.params.include_key "sqlalchemy.orm.AttributeEvents") was not used to set up the event; this is to allow backwards compatibility with existing event handlers that don’t include the `key` parameter.
New in version 2.0.
Returns:
if the event was registered with `retval=True`, the given value, or a new effective value, should be returned.
See also
[AttributeEvents](#sqlalchemy.orm.AttributeEvents "sqlalchemy.orm.AttributeEvents") - background on listener options such as propagation to subclasses.
[AttributeEvents.bulk\_replace()](#sqlalchemy.orm.AttributeEvents.bulk_replace "sqlalchemy.orm.AttributeEvents.bulk_replace")
method sqlalchemy.orm.AttributeEvents.append_wo_mutation(target: _O, value: _T, initiator: Event, *, key: EventConstants = EventConstants.NO_KEY) → None
Receive a collection append event where the collection was not actually mutated.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeClass.some_attribute, 'append_wo_mutation')
def receive_append_wo_mutation(target, value, initiator):
"listen for the 'append_wo_mutation' event"
# ... (event handling logic) ...
```
This event differs from [AttributeEvents.append()](#sqlalchemy.orm.AttributeEvents.append "sqlalchemy.orm.AttributeEvents.append") in that it is fired off for de-duplicating collections such as sets and dictionaries, when the object already exists in the target collection. The event does not have a return value and the identity of the given object cannot be changed.
The event is used for cascading objects into a [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") when the collection has already been mutated via a backref event.
- Parameters:
- **target** – the object instance receiving the event. If the listener is registered with `raw=True`, this will be the [InstanceState]($376e1901d3af4d61.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") object.
- **value** – the value that would be appended if the object did not already exist in the collection.
- **initiator** – An instance of `Event` representing the initiation of the event. May be modified from its original value by backref handlers in order to control chained event propagation, as well as be inspected for information about the source of the event.
- **key** –
When the event is established using the [AttributeEvents.include\_key](#sqlalchemy.orm.AttributeEvents.params.include_key "sqlalchemy.orm.AttributeEvents") parameter set to True, this will be the key used in the operation, such as `collection[some_key_or_index] = value`. The parameter is not passed to the event at all if the the [AttributeEvents.include\_key](#sqlalchemy.orm.AttributeEvents.params.include_key "sqlalchemy.orm.AttributeEvents") was not used to set up the event; this is to allow backwards compatibility with existing event handlers that don’t include the `key` parameter.
New in version 2.0.
Returns:
No return value is defined for this event.
New in version 1.4.15.
method bulk_replace(target: _O, values: Iterable[_T], initiator: Event, *, keys: Optional[Iterable[EventConstants]] = None) → None
Receive a collection ‘bulk replace’ event.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeClass.some_attribute, 'bulk_replace')
def receive_bulk_replace(target, values, initiator):
"listen for the 'bulk_replace' event"
# ... (event handling logic) ...
```
This event is invoked for a sequence of values as they are incoming to a bulk collection set operation, which can be modified in place before the values are treated as ORM objects. This is an “early hook” that runs before the bulk replace routine attempts to reconcile which objects are already present in the collection and which are being removed by the net replace operation.
It is typical that this method be combined with use of the [AttributeEvents.append()](#sqlalchemy.orm.AttributeEvents.append "sqlalchemy.orm.AttributeEvents.append") event. When using both of these events, note that a bulk replace operation will invoke the [AttributeEvents.append()](#sqlalchemy.orm.AttributeEvents.append "sqlalchemy.orm.AttributeEvents.append") event for all new items, even after [AttributeEvents.bulk\_replace()](#sqlalchemy.orm.AttributeEvents.bulk_replace "sqlalchemy.orm.AttributeEvents.bulk_replace") has been invoked for the collection as a whole. In order to determine if an [AttributeEvents.append()](#sqlalchemy.orm.AttributeEvents.append "sqlalchemy.orm.AttributeEvents.append") event is part of a bulk replace, use the symbol `attributes.OP_BULK_REPLACE` to test the incoming initiator:
```
from sqlalchemy.orm.attributes import OP_BULK_REPLACE
@event.listens_for(SomeObject.collection, "bulk_replace")
def process_collection(target, values, initiator):
values[:] = [_make_value(value) for value in values]
@event.listens_for(SomeObject.collection, "append", retval=True)
def process_collection(target, value, initiator):
# make sure bulk_replace didn't already do it
if initiator is None or initiator.op is not OP_BULK_REPLACE:
return _make_value(value)
else:
return value
```
New in version 1.2.
- Parameters:
- **target** – the object instance receiving the event. If the listener is registered with `raw=True`, this will be the [InstanceState]($376e1901d3af4d61.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") object.
- **value** – a sequence (e.g. a list) of the values being set. The handler can modify this list in place.
- **initiator** – An instance of `Event` representing the initiation of the event.
- **keys** –
When the event is established using the [AttributeEvents.include\_key](#sqlalchemy.orm.AttributeEvents.params.include_key "sqlalchemy.orm.AttributeEvents") parameter set to True, this will be the sequence of keys used in the operation, typically only for a dictionary update. The parameter is not passed to the event at all if the the [AttributeEvents.include\_key](#sqlalchemy.orm.AttributeEvents.params.include_key "sqlalchemy.orm.AttributeEvents") was not used to set up the event; this is to allow backwards compatibility with existing event handlers that don’t include the `key` parameter.
New in version 2.0.
See also
[AttributeEvents](#sqlalchemy.orm.AttributeEvents "sqlalchemy.orm.AttributeEvents") - background on listener options such as propagation to subclasses.
attribute sqlalchemy.orm.AttributeEvents.dispatch: _Dispatch[_ET] = <sqlalchemy.event.base.AttributeEventsDispatch object>
reference back to the _Dispatch class.
Bidirectional against _Dispatch._events
method dispose_collection(target: _O, collection: Collection[Any], collection_adapter: CollectionAdapter) → None
Receive a ‘collection dispose’ event.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeClass.some_attribute, 'dispose_collection')
def receive_dispose_collection(target, collection, collection_adapter):
"listen for the 'dispose_collection' event"
# ... (event handling logic) ...
```
This event is triggered for a collection-based attribute when a collection is replaced, that is:
```
u1.addresses.append(a1)
u1.addresses = [a2, a3] # <- old collection is disposed
```
The old collection received will contain its previous contents.
Changed in version 1.2: The collection passed to [AttributeEvents.dispose\_collection()](#sqlalchemy.orm.AttributeEvents.dispose_collection "sqlalchemy.orm.AttributeEvents.dispose_collection") will now have its contents before the dispose intact; previously, the collection would be empty.
New in version 1.0.0: the [AttributeEvents.init\_collection()](#sqlalchemy.orm.AttributeEvents.init_collection "sqlalchemy.orm.AttributeEvents.init_collection") and [AttributeEvents.dispose\_collection()](#sqlalchemy.orm.AttributeEvents.dispose_collection "sqlalchemy.orm.AttributeEvents.dispose_collection") events.
See also
[AttributeEvents](#sqlalchemy.orm.AttributeEvents "sqlalchemy.orm.AttributeEvents") - background on listener options such as propagation to subclasses.
method init_collection(target: _O, collection: Type[Collection[Any]], collection_adapter: CollectionAdapter) → None
Receive a ‘collection init’ event.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeClass.some_attribute, 'init_collection')
def receive_init_collection(target, collection, collection_adapter):
"listen for the 'init_collection' event"
# ... (event handling logic) ...
```
This event is triggered for a collection-based attribute, when the initial “empty collection” is first generated for a blank attribute, as well as for when the collection is replaced with a new one, such as via a set event.
E.g., given that `User.addresses` is a relationship-based collection, the event is triggered here:
```
u1 = User()
u1.addresses.append(a1) # <- new collection
```
and also during replace operations:
```
u1.addresses = [a2, a3] # <- new collection
```
- Parameters:
- **target** – the object instance receiving the event. If the listener is registered with `raw=True`, this will be the [InstanceState]($376e1901d3af4d61.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") object.
- **collection** – the new collection. This will always be generated from what was specified as [relationship.collection\_class]($d1a2bc9407b46431.md#sqlalchemy.orm.relationship.params.collection_class "sqlalchemy.orm.relationship"), and will always be empty.
- **collection\_adapter** – the [CollectionAdapter]($00be873adaa5613c.md#sqlalchemy.orm.collections.CollectionAdapter "sqlalchemy.orm.collections.CollectionAdapter") that will mediate internal access to the collection.
New in version 1.0.0: [AttributeEvents.init\_collection()](#sqlalchemy.orm.AttributeEvents.init_collection "sqlalchemy.orm.AttributeEvents.init_collection") and [AttributeEvents.dispose\_collection()](#sqlalchemy.orm.AttributeEvents.dispose_collection "sqlalchemy.orm.AttributeEvents.dispose_collection") events.
See also
[AttributeEvents](#sqlalchemy.orm.AttributeEvents "sqlalchemy.orm.AttributeEvents") - background on listener options such as propagation to subclasses.
[AttributeEvents.init\_scalar()](#sqlalchemy.orm.AttributeEvents.init_scalar "sqlalchemy.orm.AttributeEvents.init_scalar") - “scalar” version of this event.
method init_scalar(target: _O, value: _T, dict\: Dict[Any, Any]_) → None
Receive a scalar “init” event.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeClass.some_attribute, 'init_scalar')
def receive_init_scalar(target, value, dict_):
"listen for the 'init_scalar' event"
# ... (event handling logic) ...
```
This event is invoked when an uninitialized, unpersisted scalar attribute is accessed, e.g. read:
```
x = my_object.some_attribute
```
The ORM’s default behavior when this occurs for an un-initialized attribute is to return the value `None`; note this differs from Python’s usual behavior of raising `AttributeError`. The event here can be used to customize what value is actually returned, with the assumption that the event listener would be mirroring a default generator that is configured on the Core [Column]($e81afa1a43dcc92a.md#sqlalchemy.schema.Column "sqlalchemy.schema.Column") object as well.
Since a default generator on a [Column]($e81afa1a43dcc92a.md#sqlalchemy.schema.Column "sqlalchemy.schema.Column") might also produce a changing value such as a timestamp, the [AttributeEvents.init\_scalar()](#sqlalchemy.orm.AttributeEvents.init_scalar "sqlalchemy.orm.AttributeEvents.init_scalar") event handler can also be used to **set** the newly returned value, so that a Core-level default generation function effectively fires off only once, but at the moment the attribute is accessed on the non-persisted object. Normally, no change to the object’s state is made when an uninitialized attribute is accessed (much older SQLAlchemy versions did in fact change the object’s state).
If a default generator on a column returned a particular constant, a handler might be used as follows:
```
SOME_CONSTANT = 3.1415926
class MyClass(Base):
# ...
some_attribute = Column(Numeric, default=SOME_CONSTANT)
@event.listens_for(
MyClass.some_attribute, "init_scalar",
retval=True, propagate=True)
def _init_some_attribute(target, dict_, value):
dict_['some_attribute'] = SOME_CONSTANT
return SOME_CONSTANT
```
Above, we initialize the attribute `MyClass.some_attribute` to the value of `SOME_CONSTANT`. The above code includes the following features:
- By setting the value `SOME_CONSTANT` in the given `dict_`, we indicate that this value is to be persisted to the database. This supersedes the use of `SOME_CONSTANT` in the default generator for the [Column]($e81afa1a43dcc92a.md#sqlalchemy.schema.Column "sqlalchemy.schema.Column"). The `active_column_defaults.py` example given at [Attribute Instrumentation]($898b211e0a16e865.md#examples-instrumentation) illustrates using the same approach for a changing default, e.g. a timestamp generator. In this particular example, it is not strictly necessary to do this since `SOME_CONSTANT` would be part of the INSERT statement in either case.
- By establishing the `retval=True` flag, the value we return from the function will be returned by the attribute getter. Without this flag, the event is assumed to be a passive observer and the return value of our function is ignored.
- The `propagate=True` flag is significant if the mapped class includes inheriting subclasses, which would also make use of this event listener. Without this flag, an inheriting subclass will not use our event handler.
In the above example, the attribute set event [AttributeEvents.set()](#sqlalchemy.orm.AttributeEvents.set "sqlalchemy.orm.AttributeEvents.set") as well as the related validation feature provided by [validates]($a3905812141ddcdf.md#sqlalchemy.orm.validates "sqlalchemy.orm.validates") is **not** invoked when we apply our value to the given `dict_`. To have these events to invoke in response to our newly generated value, apply the value to the given object as a normal attribute set operation:
```
SOME_CONSTANT = 3.1415926
@event.listens_for(
MyClass.some_attribute, "init_scalar",
retval=True, propagate=True)
def _init_some_attribute(target, dict_, value):
# will also fire off attribute set events
target.some_attribute = SOME_CONSTANT
return SOME_CONSTANT
```
When multiple listeners are set up, the generation of the value is “chained” from one listener to the next by passing the value returned by the previous listener that specifies `retval=True` as the `value` argument of the next listener.
New in version 1.1.
- Parameters:
- **target** – the object instance receiving the event. If the listener is registered with `raw=True`, this will be the [InstanceState]($376e1901d3af4d61.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") object.
- **value** – the value that is to be returned before this event listener were invoked. This value begins as the value `None`, however will be the return value of the previous event handler function if multiple listeners are present.
- **dict\_** – the attribute dictionary of this mapped object. This is normally the `__dict__` of the object, but in all cases represents the destination that the attribute system uses to get at the actual value of this attribute. Placing the value in this dictionary has the effect that the value will be used in the INSERT statement generated by the unit of work.
See also
[AttributeEvents.init\_collection()](#sqlalchemy.orm.AttributeEvents.init_collection "sqlalchemy.orm.AttributeEvents.init_collection") - collection version of this event
[AttributeEvents](#sqlalchemy.orm.AttributeEvents "sqlalchemy.orm.AttributeEvents") - background on listener options such as propagation to subclasses.
[Attribute Instrumentation]($898b211e0a16e865.md#examples-instrumentation) - see the `active_column_defaults.py` example.
method sqlalchemy.orm.AttributeEvents.modified(target: _O, initiator: Event) → None
Receive a ‘modified’ event.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeClass.some_attribute, 'modified')
def receive_modified(target, initiator):
"listen for the 'modified' event"
# ... (event handling logic) ...
```
This event is triggered when the [flag\_modified()]($694f628462946390.md#sqlalchemy.orm.attributes.flag_modified "sqlalchemy.orm.attributes.flag_modified") function is used to trigger a modify event on an attribute without any specific value being set.
New in version 1.2.
- Parameters:
- **target** – the object instance receiving the event. If the listener is registered with `raw=True`, this will be the [InstanceState]($376e1901d3af4d61.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") object.
- **initiator** – An instance of `Event` representing the initiation of the event.
See also
[AttributeEvents](#sqlalchemy.orm.AttributeEvents "sqlalchemy.orm.AttributeEvents") - background on listener options such as propagation to subclasses.
method remove(target: _O, value: _T, initiator: Event, *, key: EventConstants = EventConstants.NO_KEY) → None
Receive a collection remove event.
Example argument forms:
``` from sqlalchemy import event
@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]($376e1901d3af4d61.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") object.
- **value** – the value being removed.
- **initiator** –
An instance of `Event` representing the initiation of the event. May be modified from its 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 `Event` object, and may be modified by backref handlers within a chain of backref-linked events.
- **key** –
When the event is established using the [AttributeEvents.include\_key](#sqlalchemy.orm.AttributeEvents.params.include_key "sqlalchemy.orm.AttributeEvents") parameter set to True, this will be the key used in the operation, such as `del collection[some_key_or_index]`. The parameter is not passed to the event at all if the the [AttributeEvents.include\_key](#sqlalchemy.orm.AttributeEvents.params.include_key "sqlalchemy.orm.AttributeEvents") was not used to set up the event; this is to allow backwards compatibility with existing event handlers that don’t include the `key` parameter.
New in version 2.0.
Returns:
No return value is defined for this event.
See also
[AttributeEvents](#sqlalchemy.orm.AttributeEvents "sqlalchemy.orm.AttributeEvents") - background on listener options such as propagation to subclasses.
method sqlalchemy.orm.AttributeEvents.set(target: _O, value: _T, oldvalue: _T, initiator: Event) → None
Receive a scalar set event.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeClass.some_attribute, 'set')
def receive_set(target, value, oldvalue, initiator):
"listen for the 'set' 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]($376e1901d3af4d61.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.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 `Event` representing the initiation of the event. May be modified from its 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 `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.
See also
[AttributeEvents](#sqlalchemy.orm.AttributeEvents "sqlalchemy.orm.AttributeEvents") - background on listener options such as propagation to subclasses.
class sqlalchemy.orm.QueryEvents
Represent events within the construction of a Query object.
Legacy Feature
The event methods are legacy as of SQLAlchemy 2.0, and only apply to direct use of the Query object. They are not used for statements. For events to intercept and modify 2.0 style ORM use, use the SessionEvents.do_orm_execute() hook.
The hooks are now superseded by the SessionEvents.do_orm_execute() event hook.
Members
, before_compile_delete(), , dispatch
Class signature
class (sqlalchemy.event.Events
)
method sqlalchemy.orm.QueryEvents.before_compile(query: ) → None
Receive the Query object before it is composed into a core object.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeQuery, 'before_compile')
def receive_before_compile(query):
"listen for the 'before_compile' event"
# ... (event handling logic) ...
```
Deprecated since version 1.4: The [QueryEvents.before\_compile()](#sqlalchemy.orm.QueryEvents.before_compile "sqlalchemy.orm.QueryEvents.before_compile") event is superseded by the much more capable [SessionEvents.do\_orm\_execute()](#sqlalchemy.orm.SessionEvents.do_orm_execute "sqlalchemy.orm.SessionEvents.do_orm_execute") hook. In version 1.4, the [QueryEvents.before\_compile()](#sqlalchemy.orm.QueryEvents.before_compile "sqlalchemy.orm.QueryEvents.before_compile") event is **no longer used** for ORM-level attribute loads, such as loads of deferred or expired attributes as well as relationship loaders. See the new examples in [ORM Query Events]($898b211e0a16e865.md#examples-session-orm-events) which illustrate new ways of intercepting and modifying ORM queries for the most common purpose of adding arbitrary filter criteria.
This event is intended to allow changes to the query given:
```
@event.listens_for(Query, "before_compile", retval=True)
def no_deleted(query):
for desc in query.column_descriptions:
if desc['type'] is User:
entity = desc['entity']
query = query.filter(entity.deleted == False)
return query
```
The event should normally be listened with the `retval=True` parameter set, so that the modified query may be returned.
The [QueryEvents.before\_compile()](#sqlalchemy.orm.QueryEvents.before_compile "sqlalchemy.orm.QueryEvents.before_compile") event by default will disallow “baked” queries from caching a query, if the event hook returns a new [Query]($3d0cc000ec6c7150.md#sqlalchemy.orm.Query "sqlalchemy.orm.Query") object. This affects both direct use of the baked query extension as well as its operation within lazy loaders and eager loaders for relationships. In order to re-establish the query being cached, apply the event adding the `bake_ok` flag:
```
@event.listens_for(
Query, "before_compile", retval=True, bake_ok=True)
def my_event(query):
for desc in query.column_descriptions:
if desc['type'] is User:
entity = desc['entity']
query = query.filter(entity.deleted == False)
return query
```
When `bake_ok` is set to True, the event hook will only be invoked once, and not called for subsequent invocations of a particular query that is being cached.
New in version 1.3.11: - added the “bake\_ok” flag to the [QueryEvents.before\_compile()](#sqlalchemy.orm.QueryEvents.before_compile "sqlalchemy.orm.QueryEvents.before_compile") event and disallowed caching via the “baked” extension from occurring for event handlers that return a new [Query]($3d0cc000ec6c7150.md#sqlalchemy.orm.Query "sqlalchemy.orm.Query") object if this flag is not set.
See also
[QueryEvents.before\_compile\_update()](#sqlalchemy.orm.QueryEvents.before_compile_update "sqlalchemy.orm.QueryEvents.before_compile_update")
[QueryEvents.before\_compile\_delete()](#sqlalchemy.orm.QueryEvents.before_compile_delete "sqlalchemy.orm.QueryEvents.before_compile_delete")
[Using the before\_compile event]($40dda55caf9ffcc5.md#baked-with-before-compile)
method sqlalchemy.orm.QueryEvents.before_compile_delete(query: , delete_context: BulkDelete) → None
Allow modifications to the Query object within .
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeQuery, 'before_compile_delete')
def receive_before_compile_delete(query, delete_context):
"listen for the 'before_compile_delete' event"
# ... (event handling logic) ...
```
Deprecated since version 1.4: The [QueryEvents.before\_compile\_delete()](#sqlalchemy.orm.QueryEvents.before_compile_delete "sqlalchemy.orm.QueryEvents.before_compile_delete") event is superseded by the much more capable [SessionEvents.do\_orm\_execute()](#sqlalchemy.orm.SessionEvents.do_orm_execute "sqlalchemy.orm.SessionEvents.do_orm_execute") hook.
Like the [QueryEvents.before\_compile()](#sqlalchemy.orm.QueryEvents.before_compile "sqlalchemy.orm.QueryEvents.before_compile") event, this event should be configured with `retval=True`, and the modified [Query]($3d0cc000ec6c7150.md#sqlalchemy.orm.Query "sqlalchemy.orm.Query") object returned, as in
```
@event.listens_for(Query, "before_compile_delete", retval=True)
def no_deleted(query, delete_context):
for desc in query.column_descriptions:
if desc['type'] is User:
entity = desc['entity']
query = query.filter(entity.deleted == False)
return query
```
- Parameters:
- **query** – a [Query]($3d0cc000ec6c7150.md#sqlalchemy.orm.Query "sqlalchemy.orm.Query") instance; this is also the `.query` attribute of the given “delete context” object.
- **delete\_context** – a “delete context” object which is the same kind of object as described in `QueryEvents.after_bulk_delete.delete_context`.
New in version 1.2.17.
See also
[QueryEvents.before\_compile()](#sqlalchemy.orm.QueryEvents.before_compile "sqlalchemy.orm.QueryEvents.before_compile")
[QueryEvents.before\_compile\_update()](#sqlalchemy.orm.QueryEvents.before_compile_update "sqlalchemy.orm.QueryEvents.before_compile_update")
method sqlalchemy.orm.QueryEvents.before_compile_update(query: , update_context: BulkUpdate) → None
Allow modifications to the Query object within .
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeQuery, 'before_compile_update')
def receive_before_compile_update(query, update_context):
"listen for the 'before_compile_update' event"
# ... (event handling logic) ...
```
Deprecated since version 1.4: The [QueryEvents.before\_compile\_update()](#sqlalchemy.orm.QueryEvents.before_compile_update "sqlalchemy.orm.QueryEvents.before_compile_update") event is superseded by the much more capable [SessionEvents.do\_orm\_execute()](#sqlalchemy.orm.SessionEvents.do_orm_execute "sqlalchemy.orm.SessionEvents.do_orm_execute") hook.
Like the [QueryEvents.before\_compile()](#sqlalchemy.orm.QueryEvents.before_compile "sqlalchemy.orm.QueryEvents.before_compile") event, if the event is to be used to alter the [Query]($3d0cc000ec6c7150.md#sqlalchemy.orm.Query "sqlalchemy.orm.Query") object, it should be configured with `retval=True`, and the modified [Query]($3d0cc000ec6c7150.md#sqlalchemy.orm.Query "sqlalchemy.orm.Query") object returned, as in
```
@event.listens_for(Query, "before_compile_update", retval=True)
def no_deleted(query, update_context):
for desc in query.column_descriptions:
if desc['type'] is User:
entity = desc['entity']
query = query.filter(entity.deleted == False)
update_context.values['timestamp'] = datetime.utcnow()
return query
```
The `.values` dictionary of the “update context” object can also be modified in place as illustrated above.
- Parameters:
- **query** – a [Query]($3d0cc000ec6c7150.md#sqlalchemy.orm.Query "sqlalchemy.orm.Query") instance; this is also the `.query` attribute of the given “update context” object.
- **update\_context** – an “update context” object which is the same kind of object as described in `QueryEvents.after_bulk_update.update_context`. The object has a `.values` attribute in an UPDATE context which is the dictionary of parameters passed to [Query.update()]($3d0cc000ec6c7150.md#sqlalchemy.orm.Query.update "sqlalchemy.orm.Query.update"). This dictionary can be modified to alter the VALUES clause of the resulting UPDATE statement.
New in version 1.2.17.
See also
[QueryEvents.before\_compile()](#sqlalchemy.orm.QueryEvents.before_compile "sqlalchemy.orm.QueryEvents.before_compile")
[QueryEvents.before\_compile\_delete()](#sqlalchemy.orm.QueryEvents.before_compile_delete "sqlalchemy.orm.QueryEvents.before_compile_delete")
attribute sqlalchemy.orm.QueryEvents.dispatch: _Dispatch[_ET] = <sqlalchemy.event.base.QueryEventsDispatch object>
reference back to the _Dispatch class.
Bidirectional against _Dispatch._events
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.
Object Name | Description |
---|---|
Events related to class instrumentation events. |
class sqlalchemy.orm.InstrumentationEvents
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.
Members
attribute_instrument(), , class_uninstrument(),
Class signature
class sqlalchemy.orm.InstrumentationEvents (sqlalchemy.event.Events
)
method attribute_instrument(cls: ClassManager[_O], key: _KT, inst: _O) → None
Called when an attribute is instrumented.
Example argument forms:
``` from sqlalchemy import event
@event.listens_for(SomeBaseClass, 'attribute_instrument')
def receive_attribute_instrument(cls, key, inst):
"listen for the 'attribute_instrument' event"
# ... (event handling logic) ...
```
method class_instrument(cls: ClassManager[_O]) → None
Called after the given class is instrumented.
Example argument forms:
``` from sqlalchemy import event
@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]($376e1901d3af4d61.md#sqlalchemy.orm.ClassManager "sqlalchemy.orm.ClassManager"), use `manager_of_class()`.
method class_uninstrument(cls: ClassManager[_O]) → None
Called before the given class is uninstrumented.
Example argument forms:
``` from sqlalchemy import event
@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]($376e1901d3af4d61.md#sqlalchemy.orm.ClassManager "sqlalchemy.orm.ClassManager"), use `manager_of_class()`.