class documentation

class InstanceEvents(event.Events):

Known subclasses: sqlalchemy.orm.events._InstanceEventsHold.HoldInstanceEvents

View In Hierarchy

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)
  • _orm.Mapper objects
  • the _orm.Mapper class itself and the .mapper function indicate 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 .event.listen function.

Parameters
propagate=​FalseWhen True, the event listener should be applied to all inheriting classes as well as the class which is the target of this listener.
raw=​FalseWhen 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 .InstanceEvents.load 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.
Class Method ​_accept​_with Undocumented
Class Method ​_clear Undocumented
Class Method ​_listen Undocumented
Class Method ​_new​_classmanager​_instance Undocumented
Method expire Receive an object instance after its attributes or some subset have been expired.
Method first​_init Called when the first instance of a particular mapping is called.
Method init Receive an instance when its constructor is called.
Method init​_failure Receive an instance when its constructor has been called, and raised an exception.
Method load Receive an object instance after it has been created via __new__, and after initial attribute population has occurred.
Method pickle Receive an object instance when its associated state is being pickled.
Method refresh Receive an object instance after one or more attributes have been refreshed from a query.
Method refresh​_flush 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.
Method unpickle Receive an object instance after its associated state has been unpickled.
Class Variable ​_target​_class​_doc Undocumented

Inherited from Events:

Class Method ​_remove Undocumented
Static Method ​_set​_dispatch Undocumented
@classmethod
@util.preload_module('sqlalchemy.orm')
def _accept_with(cls, target):
@classmethod
def _clear(cls):

Undocumented

@classmethod
def _listen(cls, event_key, raw=False, propagate=False, restore_load_context=False, **kw):

Undocumented

@classmethod
def _new_classmanager_instance(cls, class_, classmanager):

Undocumented

def expire(self, target, attrs):

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

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

Parameters
targetthe mapped instance. If the event is configured with raw=True, this will instead be the .InstanceState state-management object associated with the instance.
attrssequence of attribute names which were expired, or None if all attributes were expired.
def first_init(self, manager, cls):

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

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 event is invoked.

def init(self, target, args, kwargs):

Receive an instance when its constructor is called.

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 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__.

See Also

.InstanceEvents.init_failure

.InstanceEvents.load

Parameters
targetthe mapped instance. If the event is configured with raw=True, this will instead be the .InstanceState state-management object associated with the instance.
argspositional arguments passed to the __init__ method. This is passed as a tuple and is currently immutable.
kwargskeyword arguments passed to the __init__ method. This structure can be altered in place.
def init_failure(self, target, args, kwargs):

Receive an instance when its constructor has been called, and raised an exception.

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().

See Also

.InstanceEvents.init

.InstanceEvents.load

Parameters
targetthe mapped instance. If the event is configured with raw=True, this will instead be the .InstanceState state-management object associated with the instance.
argspositional arguments that were passed to the __init__ method.
kwargskeyword arguments that were passed to the __init__ method.
def load(self, target, context):

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

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 :paramref:`.InstanceEvents.restore_load_context` 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 :paramref:`.InstanceEvents.restore_load_context` and :paramref:`.SessionEvents.restore_load_context` 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 event is also available in a class-method decorator format called _orm.reconstructor.

See Also

.InstanceEvents.init

.InstanceEvents.refresh

.SessionEvents.loaded_as_persistent

:ref:`mapping_constructors`

Parameters
targetthe mapped instance. If the event is configured with raw=True, this will instead be the .InstanceState state-management object associated with the instance.
contextthe .QueryContext corresponding to the current _query.Query in progress. This argument may be None if the load does not correspond to a _query.Query, such as during .Session.merge.
def pickle(self, target, state_dict):
Receive an object instance when its associated state is being pickled.
Parameters
targetthe mapped instance. If the event is configured with raw=True, this will instead be the .InstanceState state-management object associated with the instance.
state​_dictthe dictionary returned by .InstanceState.__getstate__, containing the state to be pickled.
def refresh(self, target, context, attrs):

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

Contrast this to the .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 for background on making use of the :paramref:`.InstanceEvents.restore_load_context` parameter, in order to resolve this scenario.

See Also

.InstanceEvents.load

Parameters
targetthe mapped instance. If the event is configured with raw=True, this will instead be the .InstanceState state-management object associated with the instance.
contextthe .QueryContext corresponding to the current _query.Query in progress.
attrssequence of attribute names which were populated, or None if all column-mapped, non-deferred attributes were populated.
def refresh_flush(self, target, flush_context, attrs):

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.

This event is the same as .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 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 and .MapperEvents.after_insert are better choices.

New in version 1.0.5.
Parameters
targetthe mapped instance. If the event is configured with raw=True, this will instead be the .InstanceState state-management object associated with the instance.
flush​_contextInternal .UOWTransaction object which handles the details of the flush.
attrssequence of attribute names which were populated.
def unpickle(self, target, state_dict):
Receive an object instance after its associated state has been unpickled.
Parameters
targetthe mapped instance. If the event is configured with raw=True, this will instead be the .InstanceState state-management object associated with the instance.
state​_dictthe dictionary sent to .InstanceState.__setstate__, containing the state dictionary which was pickled.
_target_class_doc: str =

Undocumented