class documentation

tracks state information at the instance level. The :class:`.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. :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 :class:`.Session` and details about data on individual attributes. The public API in order to acquire a :class:`.InstanceState` object is to use the :func:`_sa.inspect` system:: >>> from sqlalchemy import inspect >>> insp = inspect(some_mapped_object) >>> insp.attrs.nickname.history History(added=['new nickname'], unchanged=(), deleted=['nickname']) .. seealso:: :ref:`orm_mapper_inspection_instancestate`

Method __getstate__ Undocumented
Method __init__ Undocumented
Method __setstate__ Undocumented
Method get_history Undocumented
Method get_impl Undocumented
Method unmodified_intersection Return self.unmodified.intersection(keys).
Class Variable __slots__ Undocumented
Class Variable insert_order Undocumented
Class Variable is_instance True if this object is an instance of :class:`.InstanceState`.
Class Variable key Undocumented
Class Variable load_options Undocumented
Class Variable runid 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 load_path Undocumented
Instance Variable manager Undocumented
Instance Variable modified Undocumented
Instance Variable obj Undocumented
Instance Variable parents Undocumented
Instance Variable session_id Undocumented
Property async_session Return the owning :class:`_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 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 :meth:`_query.Query.get`.
Property identity_key Return the identity key for the mapped object.
Property mapper Return the :class:`_orm.Mapper` used for this mapped object.
Property object Return the mapped object represented by this :class:`.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 :class:`.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.
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 _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 default 'weak reference' for _instance_dict
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.
Class Variable _deleted Undocumented
Class Variable _load_pending Undocumented
Class Variable _orphaned_outside_of_session Undocumented
Instance Variable _last_known_values Undocumented
Instance Variable _pending_mutations Undocumented
Instance Variable _strong_obj Undocumented
Property _attached Undocumented
Property _empty_collections Undocumented
Property _unloaded_non_object Undocumented

Inherited from InspectionAttrInfo:

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

Inherited from InspectionAttr (via InspectionAttrInfo):

Class Variable is_aliased_class True if this object is an instance of :class:`.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 :class:`.Bundle`.
Class Variable is_clause_element True if this object is an instance of :class:`_expression.ClauseElement`.
Class Variable is_mapper True if this object is an instance of :class:`_orm.Mapper`.
Class Variable is_property True if this object is an instance of :class:`.MapperProperty`.
Class Variable is_selectable Return True if this object is an instance of :class:`_expression.Selectable`.
Class Variable _is_internal_proxy True if this object is an internal proxy object.
def __getstate__(self) -> Dict[str, Any]: (source)

Undocumented

def __init__(self, obj: _O, manager: ClassManager[_O]): (source)

Undocumented

def __setstate__(self, state_dict: Dict[str, Any]): (source)

Undocumented

def get_history(self, key: str, passive: PassiveFlag) -> History: (source)

Undocumented

def get_impl(self, key: str) -> AttributeImpl: (source)

Undocumented

def unmodified_intersection(self, keys: Iterable[str]) -> Set[str]: (source)

Return self.unmodified.intersection(keys).

insert_order: Optional[int] = (source)

Undocumented

is_instance: bool = (source)

True if this object is an instance of :class:`.InstanceState`.

load_options: Tuple[ORMOption, ...] = (source)

Undocumented

Undocumented

callables = (source)

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.

Undocumented

committed_state = (source)

Undocumented

Undocumented

expired_attributes = (source)

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 = (source)

Undocumented

load_path = (source)

Undocumented

Undocumented

modified: bool = (source)

Undocumented

Undocumented

@util.memoized_property
parents = (source)

Undocumented

session_id = (source)

Undocumented

Return the owning :class:`_asyncio.AsyncSession` for this instance, or ``None`` if none available. This attribute is only non-None when the :mod:`sqlalchemy.ext.asyncio` API is in use for this ORM object. The returned :class:`_asyncio.AsyncSession` object will be a proxy for the :class:`_orm.Session` object that would be returned from the :attr:`_orm.InstanceState.session` attribute for this :class:`_orm.InstanceState`. .. versionadded:: 1.4.18 .. seealso:: :ref:`asyncio_toplevel`

@util.memoized_property
attrs: util.ReadOnlyProperties[AttributeState] = (source)

Return a namespace representing each attribute on the mapped object, including its current value and history. The returned object is an instance of :class:`.AttributeState`. This object allows inspection of the current data within an attribute as well as attribute history since the last flush.

Return ``True`` if the object is :term:`deleted`. An object that is in the deleted state is guaranteed to not be within the :attr:`.Session.identity_map` of its parent :class:`.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 :attr:`.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 :attr:`.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 :class:`.Session`, use the :attr:`.InstanceState.was_deleted` accessor. .. versionadded: 1.1 .. seealso:: :ref:`session_object_states`

Return ``True`` if the object is :term:`detached`. .. seealso:: :ref:`session_object_states`

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: bool = (source)

Return ``True`` if this object has an identity key. This should always have the same value as the expression ``state.persistent`` or ``state.detached``.

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 :meth:`_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.

Return the identity key for the mapped object. This is the key used to locate the object within the :attr:`.Session.identity_map` mapping. It contains the identity as returned by :attr:`.identity` within it.

@util.memoized_property
mapper: Mapper[_O] = (source)

Return the :class:`_orm.Mapper` used for this mapped object.

Return the mapped object represented by this :class:`.InstanceState`. Returns None if the object has been garbage collected

Return ``True`` if the object is :term:`pending`. .. seealso:: :ref:`session_object_states`

Return ``True`` if the object is :term:`persistent`. An object that is in the persistent state is guaranteed to be within the :attr:`.Session.identity_map` of its parent :class:`.Session`. .. versionchanged:: 1.1 The :attr:`.InstanceState.persistent` accessor no longer returns True for an object that was "deleted" within a flush; use the :attr:`.InstanceState.deleted` accessor to detect this state. This allows the "persistent" state to guarantee membership in the identity map. .. seealso:: :ref:`session_object_states`

Return the owning :class:`.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. .. seealso:: :attr:`_orm.InstanceState.async_session`

Return ``True`` if the object is :term:`transient`. .. seealso:: :ref:`session_object_states`

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: Set[str] = (source)

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.

Return the set of keys which have no uncommitted changes

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. .. versionadded:: 1.1 - added a local method form of :func:`.orm.util.was_deleted`. .. seealso:: :attr:`.InstanceState.deleted` - refers to the "deleted" state :func:`.orm.util.was_deleted` - standalone function :ref:`session_object_states`

@classmethod
def _commit_all_states(self, iter_: Iterable[Tuple[InstanceState[Any], _InstanceDict]], instance_dict: Optional[IdentityMap] = None): (source)

Mass / highly inlined version of commit_all().

@classmethod
def _detach_states(self, states: Iterable[InstanceState[_O]], session: Session, to_transient: bool = False): (source)

Undocumented

@classmethod
def _instance_level_callable_processor(cls, manager: ClassManager[_O], fn: _LoaderCallable, key: Any) -> _InstallLoaderCallableProto[_O]: (source)

Undocumented

def _cleanup(self, ref: weakref.ref[_O]): (source)

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_: _InstanceDict, keys: Iterable[str]): (source)

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_: _InstanceDict, instance_dict: Optional[IdentityMap] = None): (source)

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_: InstanceState[Any]): (source)

Undocumented

def _detach(self, session: Optional[Session] = None): (source)

Undocumented

def _dispose(self): (source)

Undocumented

def _expire(self, dict_: _InstanceDict, modified_set: Set[InstanceState[Any]]): (source)

Undocumented

def _expire_attributes(self, dict_: _InstanceDict, attribute_names: Iterable[str], no_loader: bool = False): (source)

Undocumented

def _get_pending_mutation(self, key: str) -> PendingCollection: (source)

Undocumented

def _initialize_instance(*mixed: Any, **kwargs: Any): (source)

Undocumented

def _instance_dict(self): (source)

default 'weak reference' for _instance_dict

def _load_expired(self, state: InstanceState[_O], passive: PassiveFlag) -> LoaderCallableStatus: (source)

__call__ allows the InstanceState to act as a deferred callable for loading expired attributes, which is also serializable (picklable).

def _modified_event(self, dict_: _InstanceDict, attr: Optional[AttributeImpl], previous: Any, collection: bool = False, is_userland: bool = False): (source)

Undocumented

def _reset(self, dict_: _InstanceDict, key: str): (source)

Remove the given attribute and any callables associated with it.

def _track_last_known_value(self, key: str): (source)

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

_deleted: bool = (source)

Undocumented

_load_pending: bool = (source)

Undocumented

_orphaned_outside_of_session: bool = (source)

Undocumented

_last_known_values: dict = (source)

Undocumented

@util.memoized_property
_pending_mutations = (source)

Undocumented

_strong_obj = (source)

Undocumented

@util.non_memoized_property
@util.preload_module('sqlalchemy.orm.session')
_attached: bool = (source)

Undocumented

@util.memoized_property
_empty_collections: Dict[str, _AdaptedCollectionProtocol] = (source)

Undocumented

@property
_unloaded_non_object: Set[str] = (source)

Undocumented