skip to content

In SQLAlchemy, how do event.listen() and @event.listens_for decide what a listener applies to, and when is propagate=True needed?

level: middleimportance: should knowfreq 30%

answer

  1. the target object sets the scope
  2. instance versus class registration
  3. unmapped base classes stay silent
  4. connect: once per new DBAPI connection

basics

~20 s

SQLAlchemy scopes a listener by the target passed in: an Engine instance or the Engine class, a Session or sessionmaker, a mapped class or attribute. Mapper, instance and attribute events reach subclasses only with propagate=True, which an unmapped base class always needs.

solid answer

~40 s

`event.listen(target, "name", fn, **kw)` and the decorator `@event.listens_for(target, "name", **kw)` do the same thing; the **target** decides the scope. An `Engine` instance covers that engine's connections, the `Engine` class every engine in the process. Pool events such as `connect` and `checkout` registered on an engine go to its pool and survive `Engine.dispose()`. Session events accept a `Session`, a `sessionmaker`, a `scoped_session` or the `Session` class (global). Mapper events take a mapped class, a `Mapper` or the `Mapper` class; attribute events take a class attribute such as `Invoice.total`. Mapper, instance and attribute events default to `propagate=False`, so a listener on an unmapped base like a `DeclarativeBase` subclass does nothing unless you pass `propagate=True`. Async objects refuse listeners: use `AsyncEngine.sync_engine` or `AsyncSession.sync_session`.

code

python · 37 lines
python
from sqlalchemy import ForeignKey, create_engine, event
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column


class Base(DeclarativeBase):
    pass


class Tenant(Base):
    __tablename__ = "tenant"
    id: Mapped[int] = mapped_column(primary_key=True)


class Invoice(Base):
    __tablename__ = "invoice"
    id: Mapped[int] = mapped_column(primary_key=True)
    tenant_id: Mapped[int] = mapped_column(ForeignKey("tenant.id"))


engine = create_engine("sqlite:///app.db")


@event.listens_for(engine, "connect")
def enable_sqlite_fks(dbapi_connection, connection_record):
    cursor = dbapi_connection.cursor()
    cursor.execute("PRAGMA foreign_keys=ON")
    cursor.close()


Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
try:
    with Session(engine) as session, session.begin():
        session.add(Invoice(id=1, tenant_id=999))
except IntegrityError as exc:
    print(exc.orig)  # FOREIGN KEY constraint failed

go deeper

for a junior

Recall the two spellings, event.listen and @event.listens_for, and that the first argument is the object or class whose events you want.

for a middle

Explain the accepted targets per event family, why class-level registration is global, and why propagate=True is required on an unmapped declarative base.

for a senior

Keep listeners scoped to the application's engine and sessionmaker, use connect for per-connection setup, and catch the silent no-op on base classes in review.

for a principal

Set a rule for where a codebase registers listeners and at which scope, so global class-level hooks never leak into libraries, tools or tests.

## Two spellings of one call SQLAlchemy's event API has two entry points that register the same thing: - `event.listen(target, identifier, fn, **kw)` attaches an existing function. - `@event.listens_for(target, identifier, **kw)` is the decorator form, convenient when the function exists only to be a listener. `event.remove(target, identifier, fn)` detaches a listener and `event.contains(...)` checks for one, which matters in tests that add listeners temporarily. The keyword arguments (`propagate`, `retval`, `raw`, and others) are interpreted by the event family the identifier belongs to. ## The target is the scope Every event family accepts a specific set of targets, and the one you pass decides which objects the listener sees. | Event family | Example identifiers | Accepted targets | |---|---|---| | Connection events | `before_cursor_execute`, `after_cursor_execute` | an `Engine` or `Connection`, instance or class | | Pool events | `connect`, `checkout`, `checkin` | an `Engine` (routed to its pool), a `Pool`, either class | | Session events | `before_flush`, `after_commit`, `do_orm_execute` | a `Session`, a `sessionmaker`, a `scoped_session`, the `Session` class | | Mapper events | `before_insert`, `before_update` | a mapped class, a `Mapper`, the `Mapper` class, an unmapped superclass with `propagate=True` | | Attribute events | `set`, `append`, `remove` | a class attribute such as `Invoice.total` | Registering on a **class** is global. `@event.listens_for(Engine, "connect")` runs for every engine the process creates, including ones a library or a test builds; `@event.listens_for(Session, "before_flush")` runs for every session. Registering on an **instance** or a `sessionmaker` keeps the hook to the objects you meant. A team usually wants the latter: a flush hook attached to the application's `sessionmaker` does not leak into a separate reporting session. ## propagate=True and inheritance Mapper, instance and attribute events default to `propagate=False`, meaning they apply to exactly the class they were registered on. Two situations need `propagate=True`: 1. **An unmapped base class.** A `DeclarativeBase` subclass or a plain mixin has no mapper. `event.listen(Base, "before_insert", fn)` is accepted without complaint, yet `fn` never fires for any mapped subclass. With `propagate=True` it fires for every mapped class that inherits from `Base`. 2. **A mapped class with mapped subclasses.** A listener on `Invoice` without `propagate=True` does not fire for a `CreditNote(Invoice)` subclass in an inheritance hierarchy. The silent failure in the first case is the classic trap: no error, no warning, simply no stamps. The documentation's own pattern for intercepting every new object of a declarative base shows the flag in place: ```python @event.listens_for(Base, "init", propagate=True) def intercept_init(instance, args, kwargs): ... ``` In practice a codebase settles on a few scoping habits: - engine-level hooks on the engine instance the application builds, next to `create_engine()`; - session hooks on the application's `sessionmaker`, which SQLAlchemy resolves to that maker's own `Session` subclass, so plain `Session()` objects elsewhere are unaffected; - mapper hooks on a shared mixin or base with `propagate=True`, so new models inherit them without registration. ## The connect event: per-connection setup Pool events describe the life of the **DBAPI connection**, the driver's own connection object that the pool keeps and reuses. `connect` fires once, at the moment the pool opens a new DBAPI connection, with `(dbapi_connection, connection_record)`. That makes it the place for settings that must hold on every physical connection, such as SQLite's foreign-key enforcement, which is off by default and must be switched on per connection: ```python @event.listens_for(engine, "connect") def enable_sqlite_fks(dbapi_connection, connection_record): cursor = dbapi_connection.cursor() cursor.execute("PRAGMA foreign_keys=ON") cursor.close() ``` The SQLite dialect documentation shows the same recipe registered on the `Engine` class. Registering on the engine instance instead keeps the `PRAGMA` away from any PostgreSQL or MySQL engine in the same process, which would reject it. Registering pool events on the `Engine` rather than its `Pool` is the documented recommendation because `Engine.dispose()` carries the listeners over to the new pool. The neighbouring pool events are easy to confuse: - `first_connect` fires exactly once per pool, for the first connection only. - `checkout` and `checkin` fire every time a connection leaves or returns to the pool. - `engine_connect` is a connection event that fires when `Engine.connect()` wraps a pooled connection in a `Connection`. ## The asyncio extension `AsyncEngine` and `AsyncSession` do not accept listeners. Passing one raises `NotImplementedError` with a message telling you to apply synchronous listeners to `AsyncEngine.sync_engine`, `AsyncConnection.sync_connection` or `AsyncSession.sync_session`. Listeners registered there are ordinary synchronous functions and cannot await anything.

  • Why does a SQLAlchemy mapper-event listener on a DeclarativeBase subclass silently never fire?
    Mapper events default to `propagate=False`, and a declarative base has no mapper of its own, so the listener is registered against a class no flush ever reports. `event.listen(Base, "before_update", fn)` raises nothing. Passing `propagate=True` applies it to every mapped subclass, including ones mapped later.
  • When should a SQLAlchemy listener use the checkout pool event instead of connect?
    Use `checkout` when the setting must be re-applied on every borrow from the pool, for example a per-request value, because `connect` runs only once per new DBAPI connection and its effect then persists through every reuse. Anything per-connection and permanent, such as an SQLite `PRAGMA`, belongs in `connect`, where it costs nothing after the first use.

  • Mapper events reach subclasses by default, so listening on Base is enough.
  • The connect event runs on every Engine.connect() call, like checkout.
  • Registering on the Engine class is the safe way to scope a hook to one engine.
  • You can pass an AsyncEngine straight to event.listen() like a sync Engine.
  • A listener on a sessionmaker fires for every Session in the process.