Events

    Subscribing to an event occurs through a single API point, the function, or alternatively the listens_for() decorator. These functions accept a target, a string identifier which identifies the event to be intercepted, and a user-defined listening function. Additional positional and keyword arguments to these two functions may be supported by specific types of events, which may specify alternate interfaces for the given event function, or provide instructions regarding secondary event targets based on the given target.

    The name of an event and the argument signature of a corresponding listener function is derived from a class bound specification method, which exists bound to a marker class that’s described in the documentation. For example, the documentation for indicates that the event name is and that a user-defined listener function should receive two positional arguments:

    To listen with the listens_for() decorator looks like:

    1. from sqlalchemy.event import listens_for
    2. from sqlalchemy.pool import Pool
    3. @listens_for(Pool, "connect")
    4. def my_on_connect(dbapi_con, connection_record):
    5. print("New DBAPI connection:", dbapi_con)

    Named Argument Styles

    There are some varieties of argument styles which can be accepted by listener functions. Taking the example of PoolEvents.connect(), this function is documented as receiving dbapi_connection and connection_record arguments. We can opt to receive these arguments by name, by establishing a listener function that accepts **keyword arguments, by passing named=True to either or listens_for():

    1. from sqlalchemy.event import listens_for
    2. from sqlalchemy.pool import Pool
    3. @listens_for(Pool, "connect", named=True)
    4. def my_on_connect(**kw):
    5. print("New DBAPI connection:", kw["dbapi_connection"])

    When using named argument passing, the names listed in the function argument specification will be used as keys in the dictionary.

    Named style passes all arguments by name regardless of the function signature, so specific arguments may be listed as well, in any order, as long as the names match up:

    Above, the presence of **kw tells that arguments should be passed to the function by name, rather than positionally.

    New in version 0.9.0: Added optional named argument dispatch to event calling.

    The function is very flexible regarding targets. It generally accepts classes, instances of those classes, and related classes or objects from which the appropriate target can be derived. For example, the above mentioned "connect" event accepts Engine classes and objects as well as classes and objects:

    1. from sqlalchemy.event import listen
    2. from sqlalchemy.pool import Pool, QueuePool
    3. from sqlalchemy import create_engine
    4. from sqlalchemy.engine import Engine
    5. def connect():
    6. return psycopg2.connect(user="ed", host="127.0.0.1", dbname="test")
    7. my_pool = QueuePool(connect)
    8. my_engine = create_engine("postgresql+psycopg2://ed@localhost/test")
    9. # associate listener with all instances of Pool
    10. listen(Pool, "connect", my_on_connect)
    11. # associate listener with all instances of Pool
    12. # via the Engine class
    13. listen(Engine, "connect", my_on_connect)
    14. # associate listener with my_pool
    15. listen(my_pool, "connect", my_on_connect)
    16. # associate listener with my_engine.pool
    17. listen(my_engine, "connect", my_on_connect)

    Modifiers

    Some listeners allow modifiers to be passed to . These modifiers sometimes provide alternate calling signatures for listeners. Such as with ORM events, some event listeners can have a return value which modifies the subsequent handling. By default, no listener ever requires a return value, but by passing retval=True this value can be supported:

    1. def validate_phone(target, value, oldvalue, initiator):
    2. """Strip non-numeric characters from a phone number"""
    3. # setup listener on UserContact.phone attribute, instructing
    4. # it to use the return value
    5. listen(UserContact.phone, "set", validate_phone, retval=True)

    Both SQLAlchemy Core and SQLAlchemy ORM feature a wide variety of event hooks:

    • Core Events - these are described in and include event hooks specific to connection pool lifecycle, SQL statement execution, transaction lifecycle, and schema creation and teardown.

    • ORM Events - these are described in ORM Events, and include event hooks specific to class and attribute instrumentation, object initialization hooks, attribute on-change hooks, session state, flush, and commit hooks, mapper initialization, object/result population, and per-instance persistence hooks.

    API Reference

    function sqlalchemy.event.listen(target: Any, identifier: str, fn: Callable[[…], Any], *args: Any, **kw: Any) → None

    Register a listener function for the given target.

    The listen() function is part of the primary interface for the SQLAlchemy event system, documented at .

    e.g.:

    • Parameters:

      • insert (bool) – The default behavior for event handlers is to append the decorated user defined function to an internal list of registered event listeners upon discovery. If a user registers a function with insert=True, SQLAlchemy will insert (prepend) the function to the internal list upon discovery. This feature is not typically used or recommended by the SQLAlchemy maintainers, but is provided to ensure certain user defined functions can run before others, such as when Changing the sql_mode in MySQL.

      • named (bool) – When using named argument passing, the names listed in the function argument specification will be used as keys in the dictionary. See .

      • once (bool) – Private/Internal API usage. Deprecated. This parameter would provide that an event function would run only once per given target. It does not however imply automatic de-registration of the listener function; associating an arbitrarily high number of listeners without explicitly removing them will cause memory to grow unbounded even if once=True is specified.

      • propagate (bool) – The propagate kwarg is available when working with ORM instrumentation and mapping events. See MapperEvents and for examples.

      • retval (bool) –

        This flag applies only to specific event listeners, each of which includes documentation explaining when it should be used. By default, no listener ever requires a return value. However, some listeners do support special behaviors for return values, and include in their documentation that the retval=True flag is necessary for a return value to be processed.

        Event listener suites that make use of listen.retval include and AttributeEvents.

    Note

    The function cannot be called at the same time that the target event is being run. This has implications for thread safety, and also means an event cannot be added from inside the listener function for itself. The list of events to be run are present inside of a mutable collection that can’t be changed during iteration.

    Event registration and removal is not intended to be a “high velocity” operation; it is a configurational operation. For systems that need to quickly associate and deassociate with events at high scale, use a mutable structure that is handled from inside of a single listener.

    See also

    listens_for()

    function sqlalchemy.event.listens_for(target: Any, identifier: str, *args: Any, **kw: Any) → Callable[[Callable[[…], Any]], Callable[[…], Any]]

    Decorate a function as a listener for the given target + identifier.

    This function generally shares the same kwargs as listens().

    e.g.:

    1. from sqlalchemy import event
    2. from sqlalchemy.schema import UniqueConstraint
    3. @event.listens_for(UniqueConstraint, "after_parent_attach")
    4. def unique_constraint_name(const, table):
    5. const.name = "uq_%s_%s" % (
    6. table.name,
    7. list(const.columns)[0].name
    8. )

    A given function can also be invoked for only the first invocation of the event using the once argument:

    1. @event.listens_for(Mapper, "before_configure", once=True)
    2. def on_config():

    Warning

    The once argument does not imply automatic de-registration of the listener function after it has been invoked a first time; a listener entry will remain associated with the target object. Associating an arbitrarily high number of listeners without explicitly removing them will cause memory to grow unbounded even if once=True is specified.

    See also

    listen() - general description of event listening

    function sqlalchemy.event.remove(target: Any, identifier: str, fn: Callable[[…], Any]) → None

    Remove an event listener.

    The arguments here should match exactly those which were sent to ; all the event registration which proceeded as a result of this call will be reverted by calling remove() with the same arguments.

    e.g.:

    Above, the listener function associated with SomeMappedClass was also propagated to subclasses of SomeMappedClass; the function will revert all of these operations.

    Note

    The remove() function cannot be called at the same time that the target event is being run. This has implications for thread safety, and also means an event cannot be removed from inside the listener function for itself. The list of events to be run are present inside of a mutable collection that can’t be changed during iteration.

    Event registration and removal is not intended to be a “high velocity” operation; it is a configurational operation. For systems that need to quickly associate and deassociate with events at high scale, use a mutable structure that is handled from inside of a single listener.

    Changed in version 1.0.0: - a collections.deque() object is now used as the container for the list of events, which explicitly disallows collection mutation while the collection is being iterated.

    See also

    function sqlalchemy.event.contains(target: Any, identifier: str, fn: Callable[[…], Any]) → bool

    Return True if the given target/ident/fn is set up to listen.