class documentation

class InstanceState(interfaces.InspectionAttrInfo):

View In Hierarchy

tracks state information at the instance level.

The .InstanceState is a key object used by the SQLAlchemy ORM in order to track the state of an object; it is created the moment an object is instantiated, typically as a result of :term:`instrumentation` which SQLAlchemy applies to the __init__() method of the class.

.InstanceState is also a semi-public object, available for runtime inspection as to the state of a mapped instance, including information such as its current status within a particular .Session and details about data on individual attributes. The public API in order to acquire a .InstanceState object is to use the _sa.inspect system:

>>> from sqlalchemy import inspect
>>> insp = inspect(some_mapped_object)
Class Method ​_commit​_all​_states Mass / highly inlined version of commit_all().
Class Method ​_detach​_states Undocumented
Class Method ​_instance​_level​_callable​_processor Undocumented
Method __getstate__ Undocumented
Method __init__ Undocumented
Method __setstate__ Undocumented
Method ​_cleanup Weakref callback cleanup.
Method ​_commit Commit attributes.
Method ​_commit​_all commit all attributes unconditionally.
Method ​_copy​_callables Undocumented
Method ​_detach Undocumented
Method ​_dispose Undocumented
Method ​_expire Undocumented
Method ​_expire​_attributes Undocumented
Method ​_get​_pending​_mutation Undocumented
Method ​_initialize​_instance Undocumented
Method ​_instance​_dict Undocumented
Method ​_load​_expired __call__ allows the InstanceState to act as a deferred callable for loading expired attributes, which is also serializable (picklable).
Method ​_modified​_event Undocumented
Method ​_reset Remove the given attribute and any callables associated with it.
Method ​_track​_last​_known​_value Track the last known value of a particular key after expiration operations.
Method get​_history Undocumented
Method get​_impl Undocumented
Method obj Undocumented
Method unmodified​_intersection Return self.unmodified.intersection(keys).
Class Variable ​_deleted Undocumented
Class Variable ​_load​_pending Undocumented
Class Variable ​_orphaned​_outside​_of​_session Undocumented
Class Variable insert​_order Undocumented
Class Variable is​_instance True if this object is an instance of .InstanceState.
Class Variable runid Undocumented
Instance Variable ​_last​_known​_values Undocumented
Instance Variable ​_pending​_mutations Undocumented
Instance Variable ​_strong​_obj Undocumented
Instance Variable callables A namespace where a per-state loader callable can be associated.
Instance Variable class​_ Undocumented
Instance Variable committed​_state Undocumented
Instance Variable expired Undocumented
Instance Variable expired​_attributes The set of keys which are 'expired' to be loaded by the manager's deferred scalar loader, assuming no pending changes.
Instance Variable identity​_token Undocumented
Instance Variable key Undocumented
Instance Variable load​_path Undocumented
Instance Variable manager Undocumented
Instance Variable modified Undocumented
Instance Variable parents Undocumented
Instance Variable session​_id Undocumented
Property ​_attached Undocumented
Property ​_empty​_collections Undocumented
Property ​_unloaded​_non​_object Undocumented
Property async​_session Return the owning _asyncio.AsyncSession for this instance, or None if none available.
Property attrs Return a namespace representing each attribute on the mapped object, including its current value and history.
Property deleted Return True if the object is :term:`deleted`.
Property detached Return True if the object is :term:`detached`.
Property dict Return the instance dict used by the object.
Property has​_identity Return True if this object has an identity key.
Property identity No summary
Property identity​_key Return the identity key for the mapped object.
Property mapper Return the _orm.Mapper used for this mapped object.
Property object Return the mapped object represented by this .InstanceState.
Property pending Return True if the object is :term:`pending`.
Property persistent Return True if the object is :term:`persistent`.
Property session Return the owning .Session for this instance, or None if none available.
Property transient Return True if the object is :term:`transient`.
Property unloaded Return the set of keys which do not have a loaded value.
Property unloaded​_expirable Return the set of keys which do not have a loaded value.
Property unmodified Return the set of keys which have no uncommitted changes
Property was​_deleted Return True if this object is or was previously in the "deleted" state and has not been reverted to persistent.

Inherited from InspectionAttrInfo:

Property info Info dictionary associated with the object, allowing user-defined data to be associated with this .InspectionAttr.

Inherited from InspectionAttr (via InspectionAttrInfo):

Class Variable __slots__ Undocumented
Class Variable ​_is​_internal​_proxy True if this object is an internal proxy object.
Class Variable is​_aliased​_class True if this object is an instance of .AliasedClass.
Class Variable is​_attribute True if this object is a Python :term:`descriptor`.
Class Variable is​_bundle True if this object is an instance of .Bundle.
Class Variable is​_clause​_element True if this object is an instance of _expression.ClauseElement.
Class Variable is​_mapper True if this object is an instance of _orm.Mapper.
Class Variable is​_property True if this object is an instance of .MapperProperty.
Class Variable is​_selectable Return True if this object is an instance of _expression.Selectable.
@classmethod
def _commit_all_states(self, iter_, instance_dict=None):
Mass / highly inlined version of commit_all().
@classmethod
def _detach_states(self, states, session, to_transient=False):

Undocumented

@classmethod
def _instance_level_callable_processor(cls, manager, fn, key):

Undocumented

def __getstate__(self):

Undocumented

def __init__(self, obj, manager):

Undocumented

def __setstate__(self, state_dict):

Undocumented

def _cleanup(self, ref):

Weakref callback cleanup.

This callable cleans out the state when it is being garbage collected.

this _cleanup assumes that there are no strong refs to us! Will not work otherwise!

def _commit(self, dict_, keys):

Commit attributes.

This is used by a partial-attribute load operation to mark committed those attributes which were refreshed from the database.

Attributes marked as "expired" can potentially remain "expired" after this step if a value was not populated in state.dict.

def _commit_all(self, dict_, instance_dict=None):

commit all attributes unconditionally.

This is used after a flush() or a full load/refresh to remove all pending state from the instance.

  • all attributes are marked as "committed"
  • the "strong dirty reference" is removed
  • the "modified" flag is set to False
  • any "expired" markers for scalar attributes loaded are removed.
  • lazy load callables for objects / collections stay

Attributes marked as "expired" can potentially remain "expired" after this step if a value was not populated in state.dict.

def _copy_callables(self, from_):

Undocumented

def _detach(self, session=None):

Undocumented

def _dispose(self):

Undocumented

def _expire(self, dict_, modified_set):

Undocumented

def _expire_attributes(self, dict_, attribute_names, no_loader=False):

Undocumented

def _get_pending_mutation(self, key):

Undocumented

def _initialize_instance(*mixed, **kwargs):

Undocumented

def _instance_dict(self):

Undocumented

def _load_expired(self, state, passive):
__call__ allows the InstanceState to act as a deferred callable for loading expired attributes, which is also serializable (picklable).
def _modified_event(self, dict_, attr, previous, collection=False, is_userland=False):

Undocumented

def _reset(self, dict_, key):
Remove the given attribute and any callables associated with it.
def _track_last_known_value(self, key):

Track the last known value of a particular key after expiration operations.

New in version 1.3.
def get_history(self, key, passive):

Undocumented

def get_impl(self, key):

Undocumented

def obj(self):

Undocumented

def unmodified_intersection(self, keys):
Return self.unmodified.intersection(keys).
_deleted: bool =

Undocumented

_load_pending: bool =

Undocumented

_orphaned_outside_of_session: bool =

Undocumented

insert_order =

Undocumented

is_instance: bool =
True if this object is an instance of .InstanceState.
runid =

Undocumented

_last_known_values =

Undocumented

@util.memoized_property
_pending_mutations =

Undocumented

_strong_obj =

Undocumented

callables =

A namespace where a per-state loader callable can be associated.

In SQLAlchemy 1.0, this is only used for lazy loaders / deferred loaders that were set up via query option.

Previously, callables was used also to indicate expired attributes by storing a link to the InstanceState itself in this dictionary. This role is now handled by the expired_attributes set.

class_ =

Undocumented

committed_state =

Undocumented

expired: bool =

Undocumented

expired_attributes: set =

The set of keys which are 'expired' to be loaded by the manager's deferred scalar loader, assuming no pending changes.

see also the unmodified collection which is intersected against this set when a refresh operation occurs.

identity_token =

Undocumented

key =

Undocumented

load_path =

Undocumented

manager =

Undocumented

modified: bool =

Undocumented

Undocumented

session_id =

Undocumented

@property
@util.preload_module('sqlalchemy.orm.session')
_attached =

Undocumented

@util.memoized_property
_empty_collections =

Undocumented

@property
_unloaded_non_object =

Undocumented

@property
async_session =

Return the owning _asyncio.AsyncSession for this instance, or None if none available.

This attribute is only non-None when the sqlalchemy.ext.asyncio API is in use for this ORM object. The returned _asyncio.AsyncSession object will be a proxy for the _orm.Session object that would be returned from the _orm.InstanceState.session attribute for this _orm.InstanceState.

New in version 1.4.18.

Return a namespace representing each attribute on the mapped object, including its current value and history.

The returned object is an instance of .AttributeState. This object allows inspection of the current data within an attribute as well as attribute history since the last flush.

@property
deleted =

Return True if the object is :term:`deleted`.

An object that is in the deleted state is guaranteed to not be within the .Session.identity_map of its parent .Session; however if the session's transaction is rolled back, the object will be restored to the persistent state and the identity map.

Note

The .InstanceState.deleted attribute refers to a specific state of the object that occurs between the "persistent" and "detached" states; once the object is :term:`detached`, the .InstanceState.deleted attribute no longer returns True; in order to detect that a state was deleted, regardless of whether or not the object is associated with a .Session, use the .InstanceState.was_deleted accessor.

@property
detached =

Return True if the object is :term:`detached`.

@property
dict =

Return the instance dict used by the object.

Under normal circumstances, this is always synonymous with the __dict__ attribute of the mapped object, unless an alternative instrumentation system has been configured.

In the case that the actual object has been garbage collected, this accessor returns a blank dictionary.

@property
has_identity =

Return True if this object has an identity key.

This should always have the same value as the expression state.persistent or state.detached.

@property
identity =

Return the mapped identity of the mapped object. This is the primary key identity as persisted by the ORM which can always be passed directly to _query.Query.get.

Returns None if the object has no primary key identity.

Note

An object which is :term:`transient` or :term:`pending` does not have a mapped identity until it is flushed, even if its attributes include primary key values.

@property
identity_key =

Return the identity key for the mapped object.

This is the key used to locate the object within the .Session.identity_map mapping. It contains the identity as returned by .identity within it.

Return the _orm.Mapper used for this mapped object.
@property
object =
Return the mapped object represented by this .InstanceState.
@property
pending =

Return True if the object is :term:`pending`.

@property
persistent =

Return True if the object is :term:`persistent`.

An object that is in the persistent state is guaranteed to be within the .Session.identity_map of its parent .Session.

Changed in version 1.1: The .InstanceState.persistent accessor no longer returns True for an object that was "deleted" within a flush; use the .InstanceState.deleted accessor to detect this state. This allows the "persistent" state to guarantee membership in the identity map.
@property
session =

Return the owning .Session for this instance, or None if none available.

Note that the result here can in some cases be different from that of obj in session; an object that's been deleted will report as not in session, however if the transaction is still in progress, this attribute will still refer to that session. Only when the transaction is completed does the object become fully detached under normal circumstances.

See Also

_orm.InstanceState.async_session

@property
transient =

Return True if the object is :term:`transient`.

@property
unloaded =

Return the set of keys which do not have a loaded value.

This includes expired attributes and any other attribute that was never populated or modified.

@property
unloaded_expirable =

Return the set of keys which do not have a loaded value.

This includes expired attributes and any other attribute that was never populated or modified.

@property
unmodified =
Return the set of keys which have no uncommitted changes
@property
was_deleted =

Return True if this object is or was previously in the "deleted" state and has not been reverted to persistent.

This flag returns True once the object was deleted in flush. When the object is expunged from the session either explicitly or via transaction commit and enters the "detached" state, this flag will continue to report True.

New in version 1.1: - added a local method form of .orm.util.was_deleted.

See Also

.InstanceState.deleted - refers to the "deleted" state

.orm.util.was_deleted - standalone function

:ref:`session_object_states`