# SQLAlchemy 2.0 Documentation

# SQLAlchemy 2.0 Documentation

# Session API

## Session and sessionmaker()

| Object Name | Description |
| --- | --- |
| ORMExecuteState | Represents a call to theSession.execute()method, as passed
to theSessionEvents.do_orm_execute()event hook. |
| Session | Manages persistence operations for ORM-mapped objects. |
| sessionmaker | A configurableSessionfactory. |
| SessionTransaction | ASession-level transaction. |
| SessionTransactionOrigin | indicates the origin of aSessionTransaction. |

   class sqlalchemy.orm.sessionmaker

*inherits from* `sqlalchemy.orm.session._SessionClassMethods`, `typing.Generic`

A configurable [Session](#sqlalchemy.orm.Session) factory.

The [sessionmaker](#sqlalchemy.orm.sessionmaker) factory generates new
[Session](#sqlalchemy.orm.Session) objects when called, creating them given
the configurational arguments established here.

e.g.:

```
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# an Engine, which the Session will use for connection
# resources
engine = create_engine("postgresql+psycopg2://scott:tiger@localhost/")

Session = sessionmaker(engine)

with Session() as session:
    session.add(some_object)
    session.add(some_other_object)
    session.commit()
```

Context manager use is optional; otherwise, the returned
[Session](#sqlalchemy.orm.Session) object may be closed explicitly via the
[Session.close()](#sqlalchemy.orm.Session.close) method.   Using a
`try:/finally:` block is optional, however will ensure that the close
takes place even if there are database errors:

```
session = Session()
try:
    session.add(some_object)
    session.add(some_other_object)
    session.commit()
finally:
    session.close()
```

[sessionmaker](#sqlalchemy.orm.sessionmaker) acts as a factory for [Session](#sqlalchemy.orm.Session)
objects in the same way as an [Engine](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Engine) acts as a factory
for [Connection](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection) objects.  In this way it also includes
a [sessionmaker.begin()](#sqlalchemy.orm.sessionmaker.begin) method, that provides a context
manager which both begins and commits a transaction, as well as closes
out the [Session](#sqlalchemy.orm.Session) when complete, rolling back the transaction
if any errors occur:

```
Session = sessionmaker(engine)

with Session.begin() as session:
    session.add(some_object)
    session.add(some_other_object)
# commits transaction, closes session
```

Added in version 1.4.

When calling upon [sessionmaker](#sqlalchemy.orm.sessionmaker) to construct a
[Session](#sqlalchemy.orm.Session), keyword arguments may also be passed to the
method; these arguments will override that of the globally configured
parameters.  Below we use a [sessionmaker](#sqlalchemy.orm.sessionmaker) bound to a certain
[Engine](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Engine) to produce a [Session](#sqlalchemy.orm.Session) that is instead
bound to a specific [Connection](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection) procured from that engine:

```
Session = sessionmaker(engine)

# bind an individual session to a connection

with engine.connect() as connection:
    with Session(bind=connection) as session:
        ...  # work with session
```

The class also includes a method [sessionmaker.configure()](#sqlalchemy.orm.sessionmaker.configure), which
can be used to specify additional keyword arguments to the factory, which
will take effect for subsequent [Session](#sqlalchemy.orm.Session) objects generated. This
is usually used to associate one or more [Engine](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Engine) objects
with an existing
[sessionmaker](#sqlalchemy.orm.sessionmaker) factory before it is first used:

```
# application starts, sessionmaker does not have
# an engine bound yet
Session = sessionmaker()

# ... later, when an engine URL is read from a configuration
# file or other events allow the engine to be created
engine = create_engine("sqlite:///foo.db")
Session.configure(bind=engine)

sess = Session()
# work with session
```

See also

[Opening and Closing a Session](https://docs.sqlalchemy.org/en/20/orm/session_basics.html#session-getting) - introductory text on creating
sessions using [sessionmaker](#sqlalchemy.orm.sessionmaker).

| Member Name | Description |
| --- | --- |
| __call__() | Produce a newSessionobject using the configuration
established in thissessionmaker. |
| __init__() | Construct a newsessionmaker. |
| begin() | Produce a context manager that both provides a newSessionas well as a transaction that commits. |
| close_all() | Closeallsessions in memory. |
| configure() | (Re)configure the arguments for this sessionmaker. |
| identity_key() | Return an identity key. |
| object_session() | Return theSessionto which an object belongs. |

   method [sqlalchemy.orm.sessionmaker.](#sqlalchemy.orm.sessionmaker)__call__(***local_kw:Any*) → _S

Produce a new [Session](#sqlalchemy.orm.Session) object using the configuration
established in this [sessionmaker](#sqlalchemy.orm.sessionmaker).

In Python, the `__call__` method is invoked on an object when
it is “called” in the same way as a function:

```
Session = sessionmaker(some_engine)
session = Session()  # invokes sessionmaker.__call__()
```

     method [sqlalchemy.orm.sessionmaker.](#sqlalchemy.orm.sessionmaker)__init__(*bind:_SessionBind|None=None*, ***, *class_:Type[_S]=<class'sqlalchemy.orm.session.Session'>*, *autoflush:bool=True*, *expire_on_commit:bool=True*, *info:_InfoType|None=None*, ***kw:Any*)

Construct a new [sessionmaker](#sqlalchemy.orm.sessionmaker).

All arguments here except for `class_` correspond to arguments
accepted by [Session](#sqlalchemy.orm.Session) directly.  See the
[Session.__init__()](#sqlalchemy.orm.Session.__init__) docstring for more details on parameters.

  Parameters:

- **bind** – a [Engine](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Engine) or other `Connectable`
  with
  which newly created [Session](#sqlalchemy.orm.Session) objects will be associated.
- **class_** – class to use in order to create new [Session](#sqlalchemy.orm.Session)
  objects.  Defaults to [Session](#sqlalchemy.orm.Session).
- **autoflush** –
  The autoflush setting to use with newly created
  [Session](#sqlalchemy.orm.Session) objects.
  See also
  [Flushing](https://docs.sqlalchemy.org/en/20/orm/session_basics.html#session-flushing) - additional background on autoflush
- **expire_on_commit=True** – the
  [Session.expire_on_commit](#sqlalchemy.orm.Session.params.expire_on_commit) setting to use
  with newly created [Session](#sqlalchemy.orm.Session) objects.
- **info** – optional dictionary of information that will be available
  via [Session.info](#sqlalchemy.orm.Session.info).  Note this dictionary is *updated*, not
  replaced, when the `info` parameter is specified to the specific
  [Session](#sqlalchemy.orm.Session) construction operation.
- ****kw** – all other keyword arguments are passed to the
  constructor of newly created [Session](#sqlalchemy.orm.Session) objects.

      method [sqlalchemy.orm.sessionmaker.](#sqlalchemy.orm.sessionmaker)begin() → AbstractContextManager[_S]

Produce a context manager that both provides a new
[Session](#sqlalchemy.orm.Session) as well as a transaction that commits.

e.g.:

```
Session = sessionmaker(some_engine)

with Session.begin() as session:
    session.add(some_object)

# commits transaction, closes session
```

Added in version 1.4.

     classmethod [sqlalchemy.orm.sessionmaker.](#sqlalchemy.orm.sessionmaker)close_all() → None

*inherited from the* `sqlalchemy.orm.session._SessionClassMethods.close_all` *method of* `sqlalchemy.orm.session._SessionClassMethods`

Close *all* sessions in memory.

Deprecated since version 1.3: The [Session.close_all()](#sqlalchemy.orm.Session.close_all) method is deprecated and will be removed in a future release.  Please refer to `close_all_sessions()`.

     method [sqlalchemy.orm.sessionmaker.](#sqlalchemy.orm.sessionmaker)configure(***new_kw:Any*) → None

(Re)configure the arguments for this sessionmaker.

e.g.:

```
Session = sessionmaker()

Session.configure(bind=create_engine("sqlite://"))
```

     classmethod [sqlalchemy.orm.sessionmaker.](#sqlalchemy.orm.sessionmaker)identity_key(*class_:Type[Any]|None=None*, *ident:Any|Tuple[Any,...]=None*, ***, *instance:Any|None=None*, *row:Row[Any]|RowMapping|None=None*, *identity_token:Any|None=None*) → _IdentityKeyType[Any]

*inherited from the* `sqlalchemy.orm.session._SessionClassMethods.identity_key` *method of* `sqlalchemy.orm.session._SessionClassMethods`

Return an identity key.

This is an alias of [identity_key()](https://docs.sqlalchemy.org/en/20/orm/mapping_api.html#sqlalchemy.orm.util.identity_key).

    classmethod [sqlalchemy.orm.sessionmaker.](#sqlalchemy.orm.sessionmaker)object_session(*instance:object*) → [Session](#sqlalchemy.orm.Session) | None

*inherited from the* `sqlalchemy.orm.session._SessionClassMethods.object_session` *method of* `sqlalchemy.orm.session._SessionClassMethods`

Return the [Session](#sqlalchemy.orm.Session) to which an object belongs.

This is an alias of [object_session()](#sqlalchemy.orm.object_session).

     class sqlalchemy.orm.ORMExecuteState

*inherits from* `sqlalchemy.util.langhelpers.MemoizedSlots`

Represents a call to the [Session.execute()](#sqlalchemy.orm.Session.execute) method, as passed
to the [SessionEvents.do_orm_execute()](https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.SessionEvents.do_orm_execute) event hook.

Added in version 1.4.

See also

[Execute Events](https://docs.sqlalchemy.org/en/20/orm/session_events.html#session-execute-events) - top level documentation on how
to use [SessionEvents.do_orm_execute()](https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.SessionEvents.do_orm_execute)

| Member Name | Description |
| --- | --- |
| __init__() | Construct a newORMExecuteState. |
| bind_arguments | The dictionary passed as theSession.execute.bind_argumentsdictionary. |
| execution_options | The complete dictionary of current execution options. |
| invoke_statement() | Execute the statement represented by thisORMExecuteState, without re-invoking events that have
already proceeded. |
| local_execution_options | Dictionary view of the execution options passed to theSession.execute()method. |
| parameters | Dictionary of parameters that was passed toSession.execute(). |
| session | TheSessionin use. |
| statement | The SQL statement being invoked. |
| update_execution_options() | Update the local execution options with new values. |

   method [sqlalchemy.orm.ORMExecuteState.](#sqlalchemy.orm.ORMExecuteState)__init__(*session:Session*, *statement:Executable*, *parameters:_CoreAnyExecuteParams|None*, *execution_options:_ExecuteOptions*, *bind_arguments:_BindArguments*, *compile_state_cls:Type[ORMCompileState]|None*, *events_todo:List[_InstanceLevelDispatch[Session]]*)

Construct a new [ORMExecuteState](#sqlalchemy.orm.ORMExecuteState).

this object is constructed internally.

    property all_mappers: [Sequence](https://docs.sqlalchemy.org/en/20/core/defaults.html#sqlalchemy.schema.Sequence)[[Mapper](https://docs.sqlalchemy.org/en/20/orm/mapping_api.html#sqlalchemy.orm.Mapper)[Any]]

Return a sequence of all [Mapper](https://docs.sqlalchemy.org/en/20/orm/mapping_api.html#sqlalchemy.orm.Mapper) objects that are
involved at the top level of this statement.

By “top level” we mean those [Mapper](https://docs.sqlalchemy.org/en/20/orm/mapping_api.html#sqlalchemy.orm.Mapper) objects that would
be represented in the result set rows for a [select()](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.select)
query, or for a [update()](https://docs.sqlalchemy.org/en/20/core/dml.html#sqlalchemy.sql.expression.update) or [delete()](https://docs.sqlalchemy.org/en/20/core/dml.html#sqlalchemy.sql.expression.delete) query,
the mapper that is the main subject of the UPDATE or DELETE.

Added in version 1.4.0b2.

See also

[ORMExecuteState.bind_mapper](#sqlalchemy.orm.ORMExecuteState.bind_mapper)

     attribute [sqlalchemy.orm.ORMExecuteState.](#sqlalchemy.orm.ORMExecuteState)bind_arguments: _BindArguments

The dictionary passed as the
[Session.execute.bind_arguments](#sqlalchemy.orm.Session.execute.params.bind_arguments) dictionary.

This dictionary may be used by extensions to [Session](#sqlalchemy.orm.Session) to pass
arguments that will assist in determining amongst a set of database
connections which one should be used to invoke this statement.

    property bind_mapper: [Mapper](https://docs.sqlalchemy.org/en/20/orm/mapping_api.html#sqlalchemy.orm.Mapper)[Any] | None

Return the [Mapper](https://docs.sqlalchemy.org/en/20/orm/mapping_api.html#sqlalchemy.orm.Mapper) that is the primary “bind” mapper.

For an [ORMExecuteState](#sqlalchemy.orm.ORMExecuteState) object invoking an ORM
statement, that is, the [ORMExecuteState.is_orm_statement](#sqlalchemy.orm.ORMExecuteState.is_orm_statement)
attribute is `True`, this attribute will return the
[Mapper](https://docs.sqlalchemy.org/en/20/orm/mapping_api.html#sqlalchemy.orm.Mapper) that is considered to be the “primary” mapper
of the statement.   The term “bind mapper” refers to the fact that
a [Session](#sqlalchemy.orm.Session) object may be “bound” to multiple
[Engine](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Engine) objects keyed to mapped classes, and the
“bind mapper” determines which of those [Engine](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Engine) objects
would be selected.

For a statement that is invoked against a single mapped class,
[ORMExecuteState.bind_mapper](#sqlalchemy.orm.ORMExecuteState.bind_mapper) is intended to be a reliable
way of getting this mapper.

Added in version 1.4.0b2.

See also

[ORMExecuteState.all_mappers](#sqlalchemy.orm.ORMExecuteState.all_mappers)

     attribute [sqlalchemy.orm.ORMExecuteState.](#sqlalchemy.orm.ORMExecuteState)execution_options: _ExecuteOptions

The complete dictionary of current execution options.

This is a merge of the statement level options with the
locally passed execution options.

See also

[ORMExecuteState.local_execution_options](#sqlalchemy.orm.ORMExecuteState.local_execution_options)

[Executable.execution_options()](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.Executable.execution_options)

[ORM Execution Options](https://docs.sqlalchemy.org/en/20/orm/queryguide/api.html#orm-queryguide-execution-options)

     method [sqlalchemy.orm.ORMExecuteState.](#sqlalchemy.orm.ORMExecuteState)invoke_statement(*statement:Executable|None=None*, *params:_CoreAnyExecuteParams|None=None*, *execution_options:OrmExecuteOptionsParameter|None=None*, *bind_arguments:_BindArguments|None=None*) → [Result](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Result)[Any]

Execute the statement represented by this
[ORMExecuteState](#sqlalchemy.orm.ORMExecuteState), without re-invoking events that have
already proceeded.

This method essentially performs a re-entrant execution of the current
statement for which the [SessionEvents.do_orm_execute()](https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.SessionEvents.do_orm_execute) event is
being currently invoked.    The use case for this is for event handlers
that want to override how the ultimate
[Result](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Result) object is returned, such as for schemes that
retrieve results from an offline cache or which concatenate results
from multiple executions.

When the [Result](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Result) object is returned by the actual
handler function within [SessionEvents.do_orm_execute()](https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.SessionEvents.do_orm_execute) and
is propagated to the calling
[Session.execute()](#sqlalchemy.orm.Session.execute) method, the remainder of the
[Session.execute()](#sqlalchemy.orm.Session.execute) method is preempted and the
[Result](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Result) object is returned to the caller of
[Session.execute()](#sqlalchemy.orm.Session.execute) immediately.

  Parameters:

- **statement** – optional statement to be invoked, in place of the
  statement currently represented by [ORMExecuteState.statement](#sqlalchemy.orm.ORMExecuteState.statement).
- **params** –
  optional dictionary of parameters or list of parameters
  which will be merged into the existing
  [ORMExecuteState.parameters](#sqlalchemy.orm.ORMExecuteState.parameters) of this [ORMExecuteState](#sqlalchemy.orm.ORMExecuteState).
  Changed in version 2.0: a list of parameter dictionaries is accepted
  for executemany executions.
- **execution_options** – optional dictionary of execution options
  will be merged into the existing
  [ORMExecuteState.execution_options](#sqlalchemy.orm.ORMExecuteState.execution_options) of this
  [ORMExecuteState](#sqlalchemy.orm.ORMExecuteState).
- **bind_arguments** – optional dictionary of bind_arguments
  which will be merged amongst the current
  [ORMExecuteState.bind_arguments](#sqlalchemy.orm.ORMExecuteState.bind_arguments)
  of this [ORMExecuteState](#sqlalchemy.orm.ORMExecuteState).

  Returns:

a [Result](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Result) object with ORM-level results.

See also

[Re-Executing Statements](https://docs.sqlalchemy.org/en/20/orm/session_events.html#do-orm-execute-re-executing) - background and examples on the
appropriate usage of [ORMExecuteState.invoke_statement()](#sqlalchemy.orm.ORMExecuteState.invoke_statement).

     property is_column_load: bool

Return True if the operation is refreshing column-oriented
attributes on an existing ORM object.

This occurs during operations such as [Session.refresh()](#sqlalchemy.orm.Session.refresh),
as well as when an attribute deferred by [defer()](https://docs.sqlalchemy.org/en/20/orm/queryguide/columns.html#sqlalchemy.orm.defer) is
being loaded, or an attribute that was expired either directly
by [Session.expire()](#sqlalchemy.orm.Session.expire) or via a commit operation is being
loaded.

Handlers will very likely not want to add any options to queries
when such an operation is occurring as the query should be a straight
primary key fetch which should not have any additional WHERE criteria,
and loader options travelling with the instance
will have already been added to the query.

Added in version 1.4.0b2.

See also

[ORMExecuteState.is_relationship_load](#sqlalchemy.orm.ORMExecuteState.is_relationship_load)

     property is_delete: bool

return True if this is a DELETE operation.

Changed in version 2.0.30: - the attribute is also True for a
[Select.from_statement()](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.Select.from_statement) construct that is itself against
a [Delete](https://docs.sqlalchemy.org/en/20/core/dml.html#sqlalchemy.sql.expression.Delete) construct, such as
`select(Entity).from_statement(delete(..))`

     property is_executemany: bool

return True if the parameters are a multi-element list of
dictionaries with more than one dictionary.

Added in version 2.0.

     property is_from_statement: bool

return True if this operation is a
[Select.from_statement()](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.Select.from_statement) operation.

This is independent from [ORMExecuteState.is_select](#sqlalchemy.orm.ORMExecuteState.is_select), as a
`select().from_statement()` construct can be used with
INSERT/UPDATE/DELETE RETURNING types of statements as well.
[ORMExecuteState.is_select](#sqlalchemy.orm.ORMExecuteState.is_select) will only be set if the
[Select.from_statement()](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.Select.from_statement) is itself against a
[Select](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.Select) construct.

Added in version 2.0.30.

     property is_insert: bool

return True if this is an INSERT operation.

Changed in version 2.0.30: - the attribute is also True for a
[Select.from_statement()](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.Select.from_statement) construct that is itself against
a [Insert](https://docs.sqlalchemy.org/en/20/core/dml.html#sqlalchemy.sql.expression.Insert) construct, such as
`select(Entity).from_statement(insert(..))`

     property is_orm_statement: bool

return True if the operation is an ORM statement.

This indicates that the select(), insert(), update(), or delete()
being invoked contains ORM entities as subjects.   For a statement
that does not have ORM entities and instead refers only to
[Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) metadata, it is invoked as a Core SQL statement
and no ORM-level automation takes place.

    property is_relationship_load: bool

Return True if this load is loading objects on behalf of a
relationship.

This means, the loader in effect is either a LazyLoader,
SelectInLoader, SubqueryLoader, or similar, and the entire
SELECT statement being emitted is on behalf of a relationship
load.

Handlers will very likely not want to add any options to queries
when such an operation is occurring, as loader options are already
capable of being propagated to relationship loaders and should
be already present.

See also

[ORMExecuteState.is_column_load](#sqlalchemy.orm.ORMExecuteState.is_column_load)

     property is_select: bool

return True if this is a SELECT operation.

Changed in version 2.0.30: - the attribute is also True for a
[Select.from_statement()](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.Select.from_statement) construct that is itself against
a [Select](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.Select) construct, such as
`select(Entity).from_statement(select(..))`

     property is_update: bool

return True if this is an UPDATE operation.

Changed in version 2.0.30: - the attribute is also True for a
[Select.from_statement()](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.Select.from_statement) construct that is itself against
a [Update](https://docs.sqlalchemy.org/en/20/core/dml.html#sqlalchemy.sql.expression.Update) construct, such as
`select(Entity).from_statement(update(..))`

     property lazy_loaded_from: [InstanceState](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.InstanceState)[Any] | None

An [InstanceState](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.InstanceState) that is using this statement execution
for a lazy load operation.

The primary rationale for this attribute is to support the horizontal
sharding extension, where it is available within specific query
execution time hooks created by this extension.   To that end, the
attribute is only intended to be meaningful at **query execution
time**, and importantly not any time prior to that, including query
compilation time.

    property load_options: [default_load_options](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.QueryContext.default_load_options) | Type[[default_load_options](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.QueryContext.default_load_options)]

Return the load_options that will be used for this execution.

    property loader_strategy_path: PathRegistry | None

Return the `PathRegistry` for the current load path.

This object represents the “path” in a query along relationships
when a particular object or collection is being loaded.

    attribute [sqlalchemy.orm.ORMExecuteState.](#sqlalchemy.orm.ORMExecuteState)local_execution_options: _ExecuteOptions

Dictionary view of the execution options passed to the
[Session.execute()](#sqlalchemy.orm.Session.execute) method.

This does not include options that may be associated with the statement
being invoked.

See also

[ORMExecuteState.execution_options](#sqlalchemy.orm.ORMExecuteState.execution_options)

     attribute [sqlalchemy.orm.ORMExecuteState.](#sqlalchemy.orm.ORMExecuteState)parameters: _CoreAnyExecuteParams | None

Dictionary of parameters that was passed to
[Session.execute()](#sqlalchemy.orm.Session.execute).

    attribute [sqlalchemy.orm.ORMExecuteState.](#sqlalchemy.orm.ORMExecuteState)session: [Session](#sqlalchemy.orm.Session)

The [Session](#sqlalchemy.orm.Session) in use.

    attribute [sqlalchemy.orm.ORMExecuteState.](#sqlalchemy.orm.ORMExecuteState)statement: [Executable](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.Executable)

The SQL statement being invoked.

For an ORM selection as would
be retrieved from [Query](https://docs.sqlalchemy.org/en/20/orm/queryguide/query.html#sqlalchemy.orm.Query), this is an instance of
[select](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.select) that was generated from the ORM query.

    property update_delete_options: default_update_options | Type[default_update_options]

Return the update_delete_options that will be used for this
execution.

    method [sqlalchemy.orm.ORMExecuteState.](#sqlalchemy.orm.ORMExecuteState)update_execution_options(***opts:Any*) → None

Update the local execution options with new values.

    property user_defined_options: [Sequence](https://docs.sqlalchemy.org/en/20/core/defaults.html#sqlalchemy.schema.Sequence)[UserDefinedOption]

The sequence of `UserDefinedOptions` that have been
associated with the statement being invoked.

     class sqlalchemy.orm.Session

*inherits from* `sqlalchemy.orm.session._SessionClassMethods`, `sqlalchemy.event.registry.EventTarget`

Manages persistence operations for ORM-mapped objects.

The [Session](#sqlalchemy.orm.Session) is **not safe for use in concurrent threads.**.
See [Is the Session thread-safe?  Is AsyncSession safe to share in concurrent tasks?](https://docs.sqlalchemy.org/en/20/orm/session_basics.html#session-faq-threadsafe) for background.

The Session’s usage paradigm is described at [Using the Session](https://docs.sqlalchemy.org/en/20/orm/session.html).

| Member Name | Description |
| --- | --- |
| __init__() | Construct a newSession. |
| add() | Place an object into thisSession. |
| add_all() | Add the given collection of instances to thisSession. |
| begin() | Begin a transaction, or nested transaction,
on thisSession, if one is not already begun. |
| begin_nested() | Begin a “nested” transaction on this Session, e.g. SAVEPOINT. |
| bind_mapper() | Associate aMapperor arbitrary Python class with a
“bind”, e.g. anEngineorConnection. |
| bind_table() | Associate aTablewith a “bind”, e.g. anEngineorConnection. |
| bulk_insert_mappings() | Perform a bulk insert of the given list of mapping dictionaries. |
| bulk_save_objects() | Perform a bulk save of the given list of objects. |
| bulk_update_mappings() | Perform a bulk update of the given list of mapping dictionaries. |
| close() | Close out the transactional resources and ORM objects used by thisSession. |
| close_all() | Closeallsessions in memory. |
| commit() | Flush pending changes and commit the current transaction. |
| connection() | Return aConnectionobject corresponding to thisSessionobject’s transactional state. |
| delete() | Mark an instance as deleted. |
| enable_relationship_loading() | Associate an object with thisSessionfor related
object loading. |
| execute() | Execute a SQL expression construct. |
| expire() | Expire the attributes on an instance. |
| expire_all() | Expires all persistent instances within this Session. |
| expunge() | Remove theinstancefrom thisSession. |
| expunge_all() | Remove all object instances from thisSession. |
| flush() | Flush all the object changes to the database. |
| get() | Return an instance based on the given primary key identifier,
orNoneif not found. |
| get_bind() | Return a “bind” to which thisSessionis bound. |
| get_nested_transaction() | Return the current nested transaction in progress, if any. |
| get_one() | Return exactly one instance based on the given primary key
identifier, or raise an exception if not found. |
| get_transaction() | Return the current root transaction in progress, if any. |
| identity_key() | Return an identity key. |
| identity_map | A mapping of object identities to objects themselves. |
| in_nested_transaction() | Return True if thisSessionhas begun a nested
transaction, e.g. SAVEPOINT. |
| in_transaction() | Return True if thisSessionhas begun a transaction. |
| info | A user-modifiable dictionary. |
| invalidate() | Close this Session, using connection invalidation. |
| is_modified() | ReturnTrueif the given instance has locally
modified attributes. |
| merge() | Copy the state of a given instance into a corresponding instance
within thisSession. |
| no_autoflush | Return a context manager that disables autoflush. |
| object_session() | Return theSessionto which an object belongs. |
| prepare() | Prepare the current transaction in progress for two phase commit. |
| query() | Return a newQueryobject corresponding to thisSession. |
| refresh() | Expire and refresh attributes on the given instance. |
| reset() | Close out the transactional resources and ORM objects used by thisSession, resetting the session to its initial state. |
| rollback() | Rollback the current transaction in progress. |
| scalar() | Execute a statement and return a scalar result. |
| scalars() | Execute a statement and return the results as scalars. |

   method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)__init__(*bind:_SessionBind|None=None*, ***, *autoflush:bool=True*, *future:Literal[True]=True*, *expire_on_commit:bool=True*, *autobegin:bool=True*, *twophase:bool=False*, *binds:Dict[_SessionBindKey,_SessionBind]|None=None*, *enable_baked_queries:bool=True*, *info:_InfoType|None=None*, *query_cls:Type[Query[Any]]|None=None*, *autocommit:Literal[False]=False*, *join_transaction_mode:JoinTransactionMode='conditional_savepoint'*, *close_resets_only:bool|_NoArg=_NoArg.NO_ARG*)

Construct a new [Session](#sqlalchemy.orm.Session).

See also the [sessionmaker](#sqlalchemy.orm.sessionmaker) function which is used to
generate a [Session](#sqlalchemy.orm.Session)-producing callable with a given
set of arguments.

  Parameters:

- **autoflush** –
  When `True`, all query operations will issue a
  [Session.flush()](#sqlalchemy.orm.Session.flush) call to this `Session` before proceeding.
  This is a convenience feature so that [Session.flush()](#sqlalchemy.orm.Session.flush) need
  not be called repeatedly in order for database queries to retrieve
  results.
  See also
  [Flushing](https://docs.sqlalchemy.org/en/20/orm/session_basics.html#session-flushing) - additional background on autoflush
- **autobegin** –
  Automatically start transactions (i.e. equivalent to
  invoking [Session.begin()](#sqlalchemy.orm.Session.begin)) when database access is
  requested by an operation.   Defaults to `True`.    Set to
  `False` to prevent a [Session](#sqlalchemy.orm.Session) from implicitly
  beginning transactions after construction, as well as after any of
  the [Session.rollback()](#sqlalchemy.orm.Session.rollback), [Session.commit()](#sqlalchemy.orm.Session.commit),
  or [Session.close()](#sqlalchemy.orm.Session.close) methods are called.
  Added in version 2.0.
  See also
  [Disabling Autobegin to Prevent Implicit Transactions](https://docs.sqlalchemy.org/en/20/orm/session_basics.html#session-autobegin-disable)
- **bind** – An optional [Engine](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Engine) or
  [Connection](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection) to
  which this `Session` should be bound. When specified, all SQL
  operations performed by this session will execute via this
  connectable.
- **binds** –
  A dictionary which may specify any number of
  [Engine](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Engine) or [Connection](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection)
  objects as the source of
  connectivity for SQL operations on a per-entity basis.   The keys
  of the dictionary consist of any series of mapped classes,
  arbitrary Python classes that are bases for mapped classes,
  [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) objects and [Mapper](https://docs.sqlalchemy.org/en/20/orm/mapping_api.html#sqlalchemy.orm.Mapper) objects.
  The
  values of the dictionary are then instances of
  [Engine](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Engine)
  or less commonly [Connection](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection) objects.
  Operations which
  proceed relative to a particular mapped class will consult this
  dictionary for the closest matching entity in order to determine
  which [Engine](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Engine) should be used for a particular SQL
  operation.    The complete heuristics for resolution are
  described at [Session.get_bind()](#sqlalchemy.orm.Session.get_bind).  Usage looks like:
  ```
  Session = sessionmaker(
      binds={
          SomeMappedClass: create_engine("postgresql+psycopg2://engine1"),
          SomeDeclarativeBase: create_engine(
              "postgresql+psycopg2://engine2"
          ),
          some_mapper: create_engine("postgresql+psycopg2://engine3"),
          some_table: create_engine("postgresql+psycopg2://engine4"),
      }
  )
  ```
  See also
  [Partitioning Strategies (e.g. multiple database backends per Session)](https://docs.sqlalchemy.org/en/20/orm/persistence_techniques.html#session-partitioning)
  [Session.bind_mapper()](#sqlalchemy.orm.Session.bind_mapper)
  [Session.bind_table()](#sqlalchemy.orm.Session.bind_table)
  [Session.get_bind()](#sqlalchemy.orm.Session.get_bind)
- **class_** – Specify an alternate class other than
  `sqlalchemy.orm.session.Session` which should be used by the
  returned class. This is the only argument that is local to the
  [sessionmaker](#sqlalchemy.orm.sessionmaker) function, and is not sent directly to the
  constructor for `Session`.
- **enable_baked_queries** –
  legacy; defaults to `True`.
  A parameter consumed
  by the [sqlalchemy.ext.baked](https://docs.sqlalchemy.org/en/20/orm/extensions/baked.html#module-sqlalchemy.ext.baked) extension to determine if
  “baked queries” should be cached, as is the normal operation
  of this extension.  When set to `False`, caching as used by
  this particular extension is disabled.
  Changed in version 1.4: The `sqlalchemy.ext.baked` extension is
  legacy and is not used by any of SQLAlchemy’s internals. This
  flag therefore only affects applications that are making explicit
  use of this extension within their own code.
- **expire_on_commit** –
  Defaults to `True`. When `True`, all
  instances will be fully expired after each [commit()](#sqlalchemy.orm.Session.commit),
  so that all attribute/object access subsequent to a completed
  transaction will load from the most recent database state.
  > See also
  >
  >
  >
  > [Committing](https://docs.sqlalchemy.org/en/20/orm/session_basics.html#session-committing)
- **future** –
  Deprecated; this flag is always True.
  See also
  [SQLAlchemy 2.0 - Major Migration Guide](https://docs.sqlalchemy.org/en/20/changelog/migration_20.html)
- **info** – optional dictionary of arbitrary data to be associated
  with this [Session](#sqlalchemy.orm.Session).  Is available via the
  [Session.info](#sqlalchemy.orm.Session.info) attribute.  Note the dictionary is copied at
  construction time so that modifications to the per-
  [Session](#sqlalchemy.orm.Session) dictionary will be local to that
  [Session](#sqlalchemy.orm.Session).
- **query_cls** – Class which should be used to create new Query
  objects, as returned by the [Session.query()](#sqlalchemy.orm.Session.query) method.
  Defaults to [Query](https://docs.sqlalchemy.org/en/20/orm/queryguide/query.html#sqlalchemy.orm.Query).
- **twophase** – When `True`, all transactions will be started as
  a “two phase” transaction, i.e. using the “two phase” semantics
  of the database in use along with an XID.  During a
  [commit()](#sqlalchemy.orm.Session.commit), after [flush()](#sqlalchemy.orm.Session.flush) has been issued for all
  attached databases, the [TwoPhaseTransaction.prepare()](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.TwoPhaseTransaction.prepare)
  method on each database’s [TwoPhaseTransaction](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.TwoPhaseTransaction) will be
  called. This allows each database to roll back the entire
  transaction, before each transaction is committed.
- **autocommit** – the “autocommit” keyword is present for backwards
  compatibility but must remain at its default value of `False`.
- **join_transaction_mode** –
  Describes the transactional behavior to
  take when a given bind is a [Connection](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection) that
  has already begun a transaction outside the scope of this
  [Session](#sqlalchemy.orm.Session); in other words the
  [Connection.in_transaction()](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection.in_transaction) method returns True.
  The following behaviors only take effect when the [Session](#sqlalchemy.orm.Session) **actually makes use of the connection given**; that is, a method
  such as [Session.execute()](#sqlalchemy.orm.Session.execute), [Session.connection()](#sqlalchemy.orm.Session.connection),
  etc. are actually invoked:
  - `"conditional_savepoint"` - this is the default.  if the given
    [Connection](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection) is begun within a transaction but
    does not have a SAVEPOINT, then `"rollback_only"` is used.
    If the [Connection](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection) is additionally within
    a SAVEPOINT, in other words
    [Connection.in_nested_transaction()](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection.in_nested_transaction) method returns
    True, then `"create_savepoint"` is used.
    `"conditional_savepoint"` behavior attempts to make use of
    savepoints in order to keep the state of the existing transaction
    unchanged, but only if there is already a savepoint in progress;
    otherwise, it is not assumed that the backend in use has adequate
    support for SAVEPOINT, as availability of this feature varies.
    `"conditional_savepoint"` also seeks to establish approximate
    backwards compatibility with previous [Session](#sqlalchemy.orm.Session)
    behavior, for applications that are not setting a specific mode. It
    is recommended that one of the explicit settings be used.
  - `"create_savepoint"` - the [Session](#sqlalchemy.orm.Session) will use
    [Connection.begin_nested()](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection.begin_nested) in all cases to create
    its own transaction.  This transaction by its nature rides
    “on top” of any existing transaction that’s opened on the given
    [Connection](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection); if the underlying database and
    the driver in use has full, non-broken support for SAVEPOINT, the
    external transaction will remain unaffected throughout the
    lifespan of the [Session](#sqlalchemy.orm.Session).
    The `"create_savepoint"` mode is the most useful for integrating
    a [Session](#sqlalchemy.orm.Session) into a test suite where an externally
    initiated transaction should remain unaffected; however, it relies
    on proper SAVEPOINT support from the underlying driver and
    database.
    Tip
    When using SQLite, the SQLite driver included through
    Python 3.11 does not handle SAVEPOINTs correctly in all cases
    without workarounds. See the sections
    [Serializable isolation / Savepoints / Transactional DDL](https://docs.sqlalchemy.org/en/20/dialects/sqlite.html#pysqlite-serializable) and [Serializable isolation / Savepoints / Transactional DDL (asyncio version)](https://docs.sqlalchemy.org/en/20/dialects/sqlite.html#aiosqlite-serializable)
    for details on current workarounds.
  - `"control_fully"` - the [Session](#sqlalchemy.orm.Session) will take
    control of the given transaction as its own;
    [Session.commit()](#sqlalchemy.orm.Session.commit) will call `.commit()` on the
    transaction, [Session.rollback()](#sqlalchemy.orm.Session.rollback) will call
    `.rollback()` on the transaction, [Session.close()](#sqlalchemy.orm.Session.close) will
    call `.rollback` on the transaction.
    Tip
    This mode of use is equivalent to how SQLAlchemy 1.4 would
    handle a [Connection](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection) given with an existing
    SAVEPOINT (i.e. [Connection.begin_nested()](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection.begin_nested)); the
    [Session](#sqlalchemy.orm.Session) would take full control of the existing
    SAVEPOINT.
  - `"rollback_only"` - the [Session](#sqlalchemy.orm.Session) will take control
    of the given transaction for `.rollback()` calls only;
    `.commit()` calls will not be propagated to the given
    transaction.  `.close()` calls will have no effect on the
    given transaction.
    Tip
    This mode of use is equivalent to how SQLAlchemy 1.4 would
    handle a [Connection](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection) given with an existing
    regular database transaction (i.e.
    [Connection.begin()](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection.begin)); the [Session](#sqlalchemy.orm.Session)
    would propagate [Session.rollback()](#sqlalchemy.orm.Session.rollback) calls to the
    underlying transaction, but not [Session.commit()](#sqlalchemy.orm.Session.commit) or
    [Session.close()](#sqlalchemy.orm.Session.close) calls.
  Added in version 2.0.0rc1.
- **close_resets_only** –
  Defaults to `True`. Determines if
  the session should reset itself after calling `.close()`
  or should pass in a no longer usable state, disabling reuse.
  Added in version 2.0.22: added flag `close_resets_only`.
  A future SQLAlchemy version may change the default value of
  this flag to `False`.
  See also
  [Closing](https://docs.sqlalchemy.org/en/20/orm/session_basics.html#session-closing) - Detail on the semantics of
  [Session.close()](#sqlalchemy.orm.Session.close) and [Session.reset()](#sqlalchemy.orm.Session.reset).

      method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)add(*instance:object*, *_warn:bool=True*) → None

Place an object into this [Session](#sqlalchemy.orm.Session).

Objects that are in the [transient](https://docs.sqlalchemy.org/en/20/glossary.html#term-transient) state when passed to the
[Session.add()](#sqlalchemy.orm.Session.add) method will move to the
[pending](https://docs.sqlalchemy.org/en/20/glossary.html#term-pending) state, until the next flush, at which point they
will move to the [persistent](https://docs.sqlalchemy.org/en/20/glossary.html#term-persistent) state.

Objects that are in the [detached](https://docs.sqlalchemy.org/en/20/glossary.html#term-detached) state when passed to the
[Session.add()](#sqlalchemy.orm.Session.add) method will move to the [persistent](https://docs.sqlalchemy.org/en/20/glossary.html#term-persistent)
state directly.

If the transaction used by the [Session](#sqlalchemy.orm.Session) is rolled back,
objects which were transient when they were passed to
[Session.add()](#sqlalchemy.orm.Session.add) will be moved back to the
[transient](https://docs.sqlalchemy.org/en/20/glossary.html#term-transient) state, and will no longer be present within this
[Session](#sqlalchemy.orm.Session).

See also

[Session.add_all()](#sqlalchemy.orm.Session.add_all)

[Adding New or Existing Items](https://docs.sqlalchemy.org/en/20/orm/session_basics.html#session-adding) - at [Basics of Using a Session](https://docs.sqlalchemy.org/en/20/orm/session_basics.html#id1)

     method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)add_all(*instances:Iterable[object]*) → None

Add the given collection of instances to this [Session](#sqlalchemy.orm.Session).

See the documentation for [Session.add()](#sqlalchemy.orm.Session.add) for a general
behavioral description.

See also

[Session.add()](#sqlalchemy.orm.Session.add)

[Adding New or Existing Items](https://docs.sqlalchemy.org/en/20/orm/session_basics.html#session-adding) - at [Basics of Using a Session](https://docs.sqlalchemy.org/en/20/orm/session_basics.html#id1)

     method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)begin(*nested:bool=False*) → [SessionTransaction](#sqlalchemy.orm.SessionTransaction)

Begin a transaction, or nested transaction,
on this [Session](#sqlalchemy.orm.Session), if one is not already begun.

The [Session](#sqlalchemy.orm.Session) object features **autobegin** behavior,
so that normally it is not necessary to call the
[Session.begin()](#sqlalchemy.orm.Session.begin)
method explicitly. However, it may be used in order to control
the scope of when the transactional state is begun.

When used to begin the outermost transaction, an error is raised
if this [Session](#sqlalchemy.orm.Session) is already inside of a transaction.

  Parameters:

**nested** – if True, begins a SAVEPOINT transaction and is
equivalent to calling [Session.begin_nested()](#sqlalchemy.orm.Session.begin_nested). For
documentation on SAVEPOINT transactions, please see
[Using SAVEPOINT](https://docs.sqlalchemy.org/en/20/orm/session_transaction.html#session-begin-nested).

  Returns:

the [SessionTransaction](#sqlalchemy.orm.SessionTransaction) object.  Note that
[SessionTransaction](#sqlalchemy.orm.SessionTransaction)
acts as a Python context manager, allowing [Session.begin()](#sqlalchemy.orm.Session.begin)
to be used in a “with” block.  See [Explicit Begin](https://docs.sqlalchemy.org/en/20/orm/session_transaction.html#session-explicit-begin) for
an example.

See also

[Auto Begin](https://docs.sqlalchemy.org/en/20/orm/session_basics.html#session-autobegin)

[Managing Transactions](https://docs.sqlalchemy.org/en/20/orm/session_transaction.html#unitofwork-transaction)

[Session.begin_nested()](#sqlalchemy.orm.Session.begin_nested)

     method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)begin_nested() → [SessionTransaction](#sqlalchemy.orm.SessionTransaction)

Begin a “nested” transaction on this Session, e.g. SAVEPOINT.

The target database(s) and associated drivers must support SQL
SAVEPOINT for this method to function correctly.

For documentation on SAVEPOINT
transactions, please see [Using SAVEPOINT](https://docs.sqlalchemy.org/en/20/orm/session_transaction.html#session-begin-nested).

  Returns:

the [SessionTransaction](#sqlalchemy.orm.SessionTransaction) object.  Note that
[SessionTransaction](#sqlalchemy.orm.SessionTransaction) acts as a context manager, allowing
[Session.begin_nested()](#sqlalchemy.orm.Session.begin_nested) to be used in a “with” block.
See [Using SAVEPOINT](https://docs.sqlalchemy.org/en/20/orm/session_transaction.html#session-begin-nested) for a usage example.

See also

[Using SAVEPOINT](https://docs.sqlalchemy.org/en/20/orm/session_transaction.html#session-begin-nested)

[Serializable isolation / Savepoints / Transactional DDL](https://docs.sqlalchemy.org/en/20/dialects/sqlite.html#pysqlite-serializable) - special workarounds required
with the SQLite driver in order for SAVEPOINT to work
correctly. For asyncio use cases, see the section
[Serializable isolation / Savepoints / Transactional DDL (asyncio version)](https://docs.sqlalchemy.org/en/20/dialects/sqlite.html#aiosqlite-serializable).

     method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)bind_mapper(*mapper:_EntityBindKey[_O]*, *bind:_SessionBind*) → None

Associate a [Mapper](https://docs.sqlalchemy.org/en/20/orm/mapping_api.html#sqlalchemy.orm.Mapper) or arbitrary Python class with a
“bind”, e.g. an [Engine](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Engine) or
[Connection](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection).

The given entity is added to a lookup used by the
[Session.get_bind()](#sqlalchemy.orm.Session.get_bind) method.

  Parameters:

- **mapper** – a [Mapper](https://docs.sqlalchemy.org/en/20/orm/mapping_api.html#sqlalchemy.orm.Mapper) object,
  or an instance of a mapped
  class, or any Python class that is the base of a set of mapped
  classes.
- **bind** – an [Engine](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Engine) or [Connection](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection)
  object.

See also

[Partitioning Strategies (e.g. multiple database backends per Session)](https://docs.sqlalchemy.org/en/20/orm/persistence_techniques.html#session-partitioning)

[Session.binds](#sqlalchemy.orm.Session.params.binds)

[Session.bind_table()](#sqlalchemy.orm.Session.bind_table)

     method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)bind_table(*table:TableClause*, *bind:Engine|Connection*) → None

Associate a [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) with a “bind”, e.g. an
[Engine](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Engine)
or [Connection](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection).

The given [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) is added to a lookup used by the
[Session.get_bind()](#sqlalchemy.orm.Session.get_bind) method.

  Parameters:

- **table** – a [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) object,
  which is typically the target
  of an ORM mapping, or is present within a selectable that is
  mapped.
- **bind** – an [Engine](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Engine) or [Connection](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection)
  object.

See also

[Partitioning Strategies (e.g. multiple database backends per Session)](https://docs.sqlalchemy.org/en/20/orm/persistence_techniques.html#session-partitioning)

[Session.binds](#sqlalchemy.orm.Session.params.binds)

[Session.bind_mapper()](#sqlalchemy.orm.Session.bind_mapper)

     method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)bulk_insert_mappings(*mapper:Mapper[Any]*, *mappings:Iterable[Dict[str,Any]]*, *return_defaults:bool=False*, *render_nulls:bool=False*) → None

Perform a bulk insert of the given list of mapping dictionaries.

Legacy Feature

This method is a legacy feature as of the 2.0 series of
SQLAlchemy.   For modern bulk INSERT and UPDATE, see
the sections [ORM Bulk INSERT Statements](https://docs.sqlalchemy.org/en/20/orm/queryguide/dml.html#orm-queryguide-bulk-insert) and
[ORM Bulk UPDATE by Primary Key](https://docs.sqlalchemy.org/en/20/orm/queryguide/dml.html#orm-queryguide-bulk-update).  The 2.0 API shares
implementation details with this method and adds new features
as well.

   Parameters:

- **mapper** – a mapped class, or the actual [Mapper](https://docs.sqlalchemy.org/en/20/orm/mapping_api.html#sqlalchemy.orm.Mapper)
  object,
  representing the single kind of object represented within the mapping
  list.
- **mappings** – a sequence of dictionaries, each one containing the
  state of the mapped row to be inserted, in terms of the attribute
  names on the mapped class.   If the mapping refers to multiple tables,
  such as a joined-inheritance mapping, each dictionary must contain all
  keys to be populated into all tables.
- **return_defaults** –
  when True, the INSERT process will be altered
  to ensure that newly generated primary key values will be fetched.
  The rationale for this parameter is typically to enable
  [Joined Table Inheritance](https://docs.sqlalchemy.org/en/20/orm/inheritance.html#joined-inheritance) mappings to
  be bulk inserted.
  Note
  for backends that don’t support RETURNING, the
  [Session.bulk_insert_mappings.return_defaults](#sqlalchemy.orm.Session.bulk_insert_mappings.params.return_defaults)
  parameter can significantly decrease performance as INSERT
  statements can no longer be batched.   See
  [“Insert Many Values” Behavior for INSERT statements](https://docs.sqlalchemy.org/en/20/core/connections.html#engine-insertmanyvalues)
  for background on which backends are affected.
- **render_nulls** –
  When True, a value of `None` will result
  in a NULL value being included in the INSERT statement, rather
  than the column being omitted from the INSERT.   This allows all
  the rows being INSERTed to have the identical set of columns which
  allows the full set of rows to be batched to the DBAPI.  Normally,
  each column-set that contains a different combination of NULL values
  than the previous row must omit a different series of columns from
  the rendered INSERT statement, which means it must be emitted as a
  separate statement.   By passing this flag, the full set of rows
  are guaranteed to be batchable into one batch; the cost however is
  that server-side defaults which are invoked by an omitted column will
  be skipped, so care must be taken to ensure that these are not
  necessary.
  Warning
  When this flag is set, **server side default SQL values will
  not be invoked** for those columns that are inserted as NULL;
  the NULL value will be sent explicitly.   Care must be taken
  to ensure that no server-side default functions need to be
  invoked for the operation as a whole.

See also

[ORM-Enabled INSERT, UPDATE, and DELETE statements](https://docs.sqlalchemy.org/en/20/orm/queryguide/dml.html)

[Session.bulk_save_objects()](#sqlalchemy.orm.Session.bulk_save_objects)

[Session.bulk_update_mappings()](#sqlalchemy.orm.Session.bulk_update_mappings)

     method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)bulk_save_objects(*objects:Iterable[object]*, *return_defaults:bool=False*, *update_changed_only:bool=True*, *preserve_order:bool=True*) → None

Perform a bulk save of the given list of objects.

Legacy Feature

This method is a legacy feature as of the 2.0 series of
SQLAlchemy.   For modern bulk INSERT and UPDATE, see
the sections [ORM Bulk INSERT Statements](https://docs.sqlalchemy.org/en/20/orm/queryguide/dml.html#orm-queryguide-bulk-insert) and
[ORM Bulk UPDATE by Primary Key](https://docs.sqlalchemy.org/en/20/orm/queryguide/dml.html#orm-queryguide-bulk-update).

For general INSERT and UPDATE of existing ORM mapped objects,
prefer standard [unit of work](https://docs.sqlalchemy.org/en/20/glossary.html#term-unit-of-work) data management patterns,
introduced in the [SQLAlchemy Unified Tutorial](https://docs.sqlalchemy.org/en/20/tutorial/index.html#unified-tutorial) at
[Data Manipulation with the ORM](https://docs.sqlalchemy.org/en/20/tutorial/orm_data_manipulation.html#tutorial-orm-data-manipulation).  SQLAlchemy 2.0
now uses [“Insert Many Values” Behavior for INSERT statements](https://docs.sqlalchemy.org/en/20/core/connections.html#engine-insertmanyvalues) with modern dialects
which solves previous issues of bulk INSERT slowness.

   Parameters:

- **objects** –
  a sequence of mapped object instances.  The mapped
  objects are persisted as is, and are **not** associated with the
  [Session](#sqlalchemy.orm.Session) afterwards.
  For each object, whether the object is sent as an INSERT or an
  UPDATE is dependent on the same rules used by the [Session](#sqlalchemy.orm.Session)
  in traditional operation; if the object has the
  `InstanceState.key`
  attribute set, then the object is assumed to be “detached” and
  will result in an UPDATE.  Otherwise, an INSERT is used.
  In the case of an UPDATE, statements are grouped based on which
  attributes have changed, and are thus to be the subject of each
  SET clause.  If `update_changed_only` is False, then all
  attributes present within each object are applied to the UPDATE
  statement, which may help in allowing the statements to be grouped
  together into a larger executemany(), and will also reduce the
  overhead of checking history on attributes.
- **return_defaults** – when True, rows that are missing values which
  generate defaults, namely integer primary key defaults and sequences,
  will be inserted **one at a time**, so that the primary key value
  is available.  In particular this will allow joined-inheritance
  and other multi-table mappings to insert correctly without the need
  to provide primary key values ahead of time; however,
  [Session.bulk_save_objects.return_defaults](#sqlalchemy.orm.Session.bulk_save_objects.params.return_defaults) **greatly
  reduces the performance gains** of the method overall.  It is strongly
  advised to please use the standard [Session.add_all()](#sqlalchemy.orm.Session.add_all)
  approach.
- **update_changed_only** – when True, UPDATE statements are rendered
  based on those attributes in each state that have logged changes.
  When False, all attributes present are rendered into the SET clause
  with the exception of primary key attributes.
- **preserve_order** – when True, the order of inserts and updates
  matches exactly the order in which the objects are given.   When
  False, common types of objects are grouped into inserts
  and updates, to allow for more batching opportunities.

See also

[ORM-Enabled INSERT, UPDATE, and DELETE statements](https://docs.sqlalchemy.org/en/20/orm/queryguide/dml.html)

[Session.bulk_insert_mappings()](#sqlalchemy.orm.Session.bulk_insert_mappings)

[Session.bulk_update_mappings()](#sqlalchemy.orm.Session.bulk_update_mappings)

     method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)bulk_update_mappings(*mapper:Mapper[Any]*, *mappings:Iterable[Dict[str,Any]]*) → None

Perform a bulk update of the given list of mapping dictionaries.

Legacy Feature

This method is a legacy feature as of the 2.0 series of
SQLAlchemy.   For modern bulk INSERT and UPDATE, see
the sections [ORM Bulk INSERT Statements](https://docs.sqlalchemy.org/en/20/orm/queryguide/dml.html#orm-queryguide-bulk-insert) and
[ORM Bulk UPDATE by Primary Key](https://docs.sqlalchemy.org/en/20/orm/queryguide/dml.html#orm-queryguide-bulk-update).  The 2.0 API shares
implementation details with this method and adds new features
as well.

   Parameters:

- **mapper** – a mapped class, or the actual [Mapper](https://docs.sqlalchemy.org/en/20/orm/mapping_api.html#sqlalchemy.orm.Mapper)
  object,
  representing the single kind of object represented within the mapping
  list.
- **mappings** – a sequence of dictionaries, each one containing the
  state of the mapped row to be updated, in terms of the attribute names
  on the mapped class.   If the mapping refers to multiple tables, such
  as a joined-inheritance mapping, each dictionary may contain keys
  corresponding to all tables.   All those keys which are present and
  are not part of the primary key are applied to the SET clause of the
  UPDATE statement; the primary key values, which are required, are
  applied to the WHERE clause.

See also

[ORM-Enabled INSERT, UPDATE, and DELETE statements](https://docs.sqlalchemy.org/en/20/orm/queryguide/dml.html)

[Session.bulk_insert_mappings()](#sqlalchemy.orm.Session.bulk_insert_mappings)

[Session.bulk_save_objects()](#sqlalchemy.orm.Session.bulk_save_objects)

     method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)close() → None

Close out the transactional resources and ORM objects used by this
[Session](#sqlalchemy.orm.Session).

This expunges all ORM objects associated with this
[Session](#sqlalchemy.orm.Session), ends any transaction in progress and
[releases](https://docs.sqlalchemy.org/en/20/glossary.html#term-releases) any [Connection](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection) objects which this
[Session](#sqlalchemy.orm.Session) itself has checked out from associated
[Engine](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Engine) objects. The operation then leaves the
[Session](#sqlalchemy.orm.Session) in a state which it may be used again.

Tip

In the default running mode the [Session.close()](#sqlalchemy.orm.Session.close)
method **does not prevent the Session from being used again**.
The [Session](#sqlalchemy.orm.Session) itself does not actually have a
distinct “closed” state; it merely means
the [Session](#sqlalchemy.orm.Session) will release all database connections
and ORM objects.

Setting the parameter [Session.close_resets_only](#sqlalchemy.orm.Session.params.close_resets_only)
to `False` will instead make the `close` final, meaning that
any further action on the session will be forbidden.

Changed in version 1.4: The [Session.close()](#sqlalchemy.orm.Session.close) method does not
immediately create a new [SessionTransaction](#sqlalchemy.orm.SessionTransaction) object;
instead, the new [SessionTransaction](#sqlalchemy.orm.SessionTransaction) is created only if
the [Session](#sqlalchemy.orm.Session) is used again for a database operation.

See also

[Closing](https://docs.sqlalchemy.org/en/20/orm/session_basics.html#session-closing) - detail on the semantics of
[Session.close()](#sqlalchemy.orm.Session.close) and [Session.reset()](#sqlalchemy.orm.Session.reset).

[Session.reset()](#sqlalchemy.orm.Session.reset) - a similar method that behaves like
`close()` with  the parameter
[Session.close_resets_only](#sqlalchemy.orm.Session.params.close_resets_only) set to `True`.

     classmethod [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)close_all() → None

*inherited from the* `sqlalchemy.orm.session._SessionClassMethods.close_all` *method of* `sqlalchemy.orm.session._SessionClassMethods`

Close *all* sessions in memory.

Deprecated since version 1.3: The [Session.close_all()](#sqlalchemy.orm.Session.close_all) method is deprecated and will be removed in a future release.  Please refer to `close_all_sessions()`.

     method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)commit() → None

Flush pending changes and commit the current transaction.

When the COMMIT operation is complete, all objects are fully
[expired](https://docs.sqlalchemy.org/en/20/glossary.html#term-expired), erasing their internal contents, which will be
automatically re-loaded when the objects are next accessed. In the
interim, these objects are in an expired state and will not function if
they are [detached](https://docs.sqlalchemy.org/en/20/glossary.html#term-detached) from the [Session](#sqlalchemy.orm.Session). Additionally,
this re-load operation is not supported when using asyncio-oriented
APIs. The [Session.expire_on_commit](#sqlalchemy.orm.Session.params.expire_on_commit) parameter may be used
to disable this behavior.

When there is no transaction in place for the [Session](#sqlalchemy.orm.Session),
indicating that no operations were invoked on this [Session](#sqlalchemy.orm.Session)
since the previous call to [Session.commit()](#sqlalchemy.orm.Session.commit), the method will
begin and commit an internal-only “logical” transaction, that does not
normally affect the database unless pending flush changes were
detected, but will still invoke event handlers and object expiration
rules.

The outermost database transaction is committed unconditionally,
automatically releasing any SAVEPOINTs in effect.

See also

[Committing](https://docs.sqlalchemy.org/en/20/orm/session_basics.html#session-committing)

[Managing Transactions](https://docs.sqlalchemy.org/en/20/orm/session_transaction.html#unitofwork-transaction)

[Preventing Implicit IO when Using AsyncSession](https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html#asyncio-orm-avoid-lazyloads)

     method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)connection(*bind_arguments:_BindArguments|None=None*, *execution_options:CoreExecuteOptionsParameter|None=None*) → [Connection](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection)

Return a [Connection](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection) object corresponding to this
[Session](#sqlalchemy.orm.Session) object’s transactional state.

Either the [Connection](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection) corresponding to the current
transaction is returned, or if no transaction is in progress, a new
one is begun and the [Connection](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection)
returned (note that no
transactional state is established with the DBAPI until the first
SQL statement is emitted).

Ambiguity in multi-bind or unbound [Session](#sqlalchemy.orm.Session) objects can be
resolved through any of the optional keyword arguments.   This
ultimately makes usage of the [get_bind()](#sqlalchemy.orm.Session.get_bind) method for resolution.

  Parameters:

- **bind_arguments** – dictionary of bind arguments.  May include
  “mapper”, “bind”, “clause”, other custom arguments that are passed
  to [Session.get_bind()](#sqlalchemy.orm.Session.get_bind).
- **execution_options** –
  a dictionary of execution options that will
  be passed to [Connection.execution_options()](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection.execution_options), **when the
  connection is first procured only**.   If the connection is already
  present within the [Session](#sqlalchemy.orm.Session), a warning is emitted and
  the arguments are ignored.
  See also
  [Setting Transaction Isolation Levels / DBAPI AUTOCOMMIT](https://docs.sqlalchemy.org/en/20/orm/session_transaction.html#session-transaction-isolation)

      method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)delete(*instance:object*) → None

Mark an instance as deleted.

The object is assumed to be either [persistent](https://docs.sqlalchemy.org/en/20/glossary.html#term-persistent) or
[detached](https://docs.sqlalchemy.org/en/20/glossary.html#term-detached) when passed; after the method is called, the
object will remain in the [persistent](https://docs.sqlalchemy.org/en/20/glossary.html#term-persistent) state until the next
flush proceeds.  During this time, the object will also be a member
of the [Session.deleted](#sqlalchemy.orm.Session.deleted) collection.

When the next flush proceeds, the object will move to the
[deleted](https://docs.sqlalchemy.org/en/20/glossary.html#term-deleted) state, indicating a `DELETE` statement was emitted
for its row within the current transaction.   When the transaction
is successfully committed,
the deleted object is moved to the [detached](https://docs.sqlalchemy.org/en/20/glossary.html#term-detached) state and is
no longer present within this [Session](#sqlalchemy.orm.Session).

See also

[Deleting](https://docs.sqlalchemy.org/en/20/orm/session_basics.html#session-deleting) - at [Basics of Using a Session](https://docs.sqlalchemy.org/en/20/orm/session_basics.html#id1)

     property deleted: IdentitySet

The set of all instances marked as ‘deleted’ within this `Session`

    property dirty: IdentitySet

The set of all persistent instances considered dirty.

E.g.:

```
some_mapped_object in session.dirty
```

Instances are considered dirty when they were modified but not
deleted.

Note that this ‘dirty’ calculation is ‘optimistic’; most
attribute-setting or collection modification operations will
mark an instance as ‘dirty’ and place it in this set, even if
there is no net change to the attribute’s value.  At flush
time, the value of each attribute is compared to its
previously saved value, and if there’s no net change, no SQL
operation will occur (this is a more expensive operation so
it’s only done at flush time).

To check if an instance has actionable net changes to its
attributes, use the [Session.is_modified()](#sqlalchemy.orm.Session.is_modified) method.

    method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)enable_relationship_loading(*obj:object*) → None

Associate an object with this [Session](#sqlalchemy.orm.Session) for related
object loading.

Warning

[enable_relationship_loading()](#sqlalchemy.orm.Session.enable_relationship_loading) exists to serve special
use cases and is not recommended for general use.

Accesses of attributes mapped with [relationship()](https://docs.sqlalchemy.org/en/20/orm/relationship_api.html#sqlalchemy.orm.relationship)
will attempt to load a value from the database using this
[Session](#sqlalchemy.orm.Session) as the source of connectivity.  The values
will be loaded based on foreign key and primary key values
present on this object - if not present, then those relationships
will be unavailable.

The object will be attached to this session, but will
**not** participate in any persistence operations; its state
for almost all purposes will remain either “transient” or
“detached”, except for the case of relationship loading.

Also note that backrefs will often not work as expected.
Altering a relationship-bound attribute on the target object
may not fire off a backref event, if the effective value
is what was already loaded from a foreign-key-holding value.

The [Session.enable_relationship_loading()](#sqlalchemy.orm.Session.enable_relationship_loading) method is
similar to the `load_on_pending` flag on [relationship()](https://docs.sqlalchemy.org/en/20/orm/relationship_api.html#sqlalchemy.orm.relationship).
Unlike that flag, [Session.enable_relationship_loading()](#sqlalchemy.orm.Session.enable_relationship_loading) allows
an object to remain transient while still being able to load
related items.

To make a transient object associated with a [Session](#sqlalchemy.orm.Session)
via [Session.enable_relationship_loading()](#sqlalchemy.orm.Session.enable_relationship_loading) pending, add
it to the [Session](#sqlalchemy.orm.Session) using [Session.add()](#sqlalchemy.orm.Session.add) normally.
If the object instead represents an existing identity in the database,
it should be merged using [Session.merge()](#sqlalchemy.orm.Session.merge).

[Session.enable_relationship_loading()](#sqlalchemy.orm.Session.enable_relationship_loading) does not improve
behavior when the ORM is used normally - object references should be
constructed at the object level, not at the foreign key level, so
that they are present in an ordinary way before flush()
proceeds.  This method is not intended for general use.

See also

[relationship.load_on_pending](https://docs.sqlalchemy.org/en/20/orm/relationship_api.html#sqlalchemy.orm.relationship.params.load_on_pending) - this flag
allows per-relationship loading of many-to-ones on items that
are pending.

[make_transient_to_detached()](#sqlalchemy.orm.make_transient_to_detached) - allows for an object to
be added to a [Session](#sqlalchemy.orm.Session) without SQL emitted, which then
will unexpire attributes on access.

     method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)execute(*statement:Executable*, *params:_CoreAnyExecuteParams|None=None*, ***, *execution_options:OrmExecuteOptionsParameter={}*, *bind_arguments:_BindArguments|None=None*, *_parent_execute_state:Any|None=None*, *_add_event:Any|None=None*) → [Result](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Result)[Any]

Execute a SQL expression construct.

Returns a [Result](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Result) object representing
results of the statement execution.

E.g.:

```
from sqlalchemy import select

result = session.execute(select(User).where(User.id == 5))
```

The API contract of [Session.execute()](#sqlalchemy.orm.Session.execute) is similar to that
of [Connection.execute()](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection.execute), the [2.0 style](https://docs.sqlalchemy.org/en/20/glossary.html#term-2.0-style) version
of [Connection](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection).

Changed in version 1.4: the [Session.execute()](#sqlalchemy.orm.Session.execute) method is
now the primary point of ORM statement execution when using
[2.0 style](https://docs.sqlalchemy.org/en/20/glossary.html#term-2.0-style) ORM usage.

   Parameters:

- **statement** – An executable statement (i.e. an [Executable](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.Executable) expression
  such as [select()](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.select)).
- **params** – Optional dictionary, or list of dictionaries, containing
  bound parameter values.   If a single dictionary, single-row
  execution occurs; if a list of dictionaries, an
  “executemany” will be invoked.  The keys in each dictionary
  must correspond to parameter names present in the statement.
- **execution_options** –
  optional dictionary of execution options,
  which will be associated with the statement execution.  This
  dictionary can provide a subset of the options that are accepted
  by [Connection.execution_options()](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection.execution_options), and may also
  provide additional options understood only in an ORM context.
  See also
  [ORM Execution Options](https://docs.sqlalchemy.org/en/20/orm/queryguide/api.html#orm-queryguide-execution-options) - ORM-specific execution
  options
- **bind_arguments** – dictionary of additional arguments to determine
  the bind.  May include “mapper”, “bind”, or other custom arguments.
  Contents of this dictionary are passed to the
  [Session.get_bind()](#sqlalchemy.orm.Session.get_bind) method.

  Returns:

a [Result](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Result) object.

      method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)expire(*instance:object*, *attribute_names:Iterable[str]|None=None*) → None

Expire the attributes on an instance.

Marks the attributes of an instance as out of date. When an expired
attribute is next accessed, a query will be issued to the
[Session](#sqlalchemy.orm.Session) object’s current transactional context in order to
load all expired attributes for the given instance.   Note that
a highly isolated transaction will return the same values as were
previously read in that same transaction, regardless of changes
in database state outside of that transaction.

To expire all objects in the [Session](#sqlalchemy.orm.Session) simultaneously,
use [Session.expire_all()](#sqlalchemy.orm.Session.expire_all).

The [Session](#sqlalchemy.orm.Session) object’s default behavior is to
expire all state whenever the [Session.rollback()](#sqlalchemy.orm.Session.rollback)
or [Session.commit()](#sqlalchemy.orm.Session.commit) methods are called, so that new
state can be loaded for the new transaction.   For this reason,
calling [Session.expire()](#sqlalchemy.orm.Session.expire) only makes sense for the specific
case that a non-ORM SQL statement was emitted in the current
transaction.

  Parameters:

- **instance** – The instance to be refreshed.
- **attribute_names** – optional list of string attribute names
  indicating a subset of attributes to be expired.

See also

[Refreshing / Expiring](https://docs.sqlalchemy.org/en/20/orm/session_state_management.html#session-expire) - introductory material

[Session.expire()](#sqlalchemy.orm.Session.expire)

[Session.refresh()](#sqlalchemy.orm.Session.refresh)

[Query.populate_existing()](https://docs.sqlalchemy.org/en/20/orm/queryguide/query.html#sqlalchemy.orm.Query.populate_existing)

     method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)expire_all() → None

Expires all persistent instances within this Session.

When any attributes on a persistent instance is next accessed,
a query will be issued using the
[Session](#sqlalchemy.orm.Session) object’s current transactional context in order to
load all expired attributes for the given instance.   Note that
a highly isolated transaction will return the same values as were
previously read in that same transaction, regardless of changes
in database state outside of that transaction.

To expire individual objects and individual attributes
on those objects, use [Session.expire()](#sqlalchemy.orm.Session.expire).

The [Session](#sqlalchemy.orm.Session) object’s default behavior is to
expire all state whenever the [Session.rollback()](#sqlalchemy.orm.Session.rollback)
or [Session.commit()](#sqlalchemy.orm.Session.commit) methods are called, so that new
state can be loaded for the new transaction.   For this reason,
calling [Session.expire_all()](#sqlalchemy.orm.Session.expire_all) is not usually needed,
assuming the transaction is isolated.

See also

[Refreshing / Expiring](https://docs.sqlalchemy.org/en/20/orm/session_state_management.html#session-expire) - introductory material

[Session.expire()](#sqlalchemy.orm.Session.expire)

[Session.refresh()](#sqlalchemy.orm.Session.refresh)

[Query.populate_existing()](https://docs.sqlalchemy.org/en/20/orm/queryguide/query.html#sqlalchemy.orm.Query.populate_existing)

     method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)expunge(*instance:object*) → None

Remove the instance from this `Session`.

This will free all internal references to the instance.  Cascading
will be applied according to the *expunge* cascade rule.

    method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)expunge_all() → None

Remove all object instances from this `Session`.

This is equivalent to calling `expunge(obj)` on all objects in this
`Session`.

    method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)flush(*objects:Sequence[Any]|None=None*) → None

Flush all the object changes to the database.

Writes out all pending object creations, deletions and modifications
to the database as INSERTs, DELETEs, UPDATEs, etc.  Operations are
automatically ordered by the Session’s unit of work dependency
solver.

Database operations will be issued in the current transactional
context and do not affect the state of the transaction, unless an
error occurs, in which case the entire transaction is rolled back.
You may flush() as often as you like within a transaction to move
changes from Python to the database’s transaction buffer.

  Parameters:

**objects** –

Optional; restricts the flush operation to operate
only on elements that are in the given collection.

This feature is for an extremely narrow set of use cases where
particular objects may need to be operated upon before the
full flush() occurs.  It is not intended for general use.

      method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)get(*entity:_EntityBindKey[_O]*, *ident:_PKIdentityArgument*, ***, *options:Sequence[ORMOption]|None=None*, *populate_existing:bool=False*, *with_for_update:ForUpdateParameter=None*, *identity_token:Any|None=None*, *execution_options:OrmExecuteOptionsParameter={}*, *bind_arguments:_BindArguments|None=None*) → _O | None

Return an instance based on the given primary key identifier,
or `None` if not found.

E.g.:

```
my_user = session.get(User, 5)

some_object = session.get(VersionedFoo, (5, 10))

some_object = session.get(VersionedFoo, {"id": 5, "version_id": 10})
```

Added in version 1.4: Added [Session.get()](#sqlalchemy.orm.Session.get), which is moved
from the now legacy [Query.get()](https://docs.sqlalchemy.org/en/20/orm/queryguide/query.html#sqlalchemy.orm.Query.get) method.

[Session.get()](#sqlalchemy.orm.Session.get) is special in that it provides direct
access to the identity map of the [Session](#sqlalchemy.orm.Session).
If the given primary key identifier is present
in the local identity map, the object is returned
directly from this collection and no SQL is emitted,
unless the object has been marked fully expired.
If not present,
a SELECT is performed in order to locate the object.

[Session.get()](#sqlalchemy.orm.Session.get) also will perform a check if
the object is present in the identity map and
marked as expired - a SELECT
is emitted to refresh the object as well as to
ensure that the row is still present.
If not, [ObjectDeletedError](https://docs.sqlalchemy.org/en/20/orm/exceptions.html#sqlalchemy.orm.exc.ObjectDeletedError) is raised.

  Parameters:

- **entity** – a mapped class or [Mapper](https://docs.sqlalchemy.org/en/20/orm/mapping_api.html#sqlalchemy.orm.Mapper) indicating the
  type of entity to be loaded.
- **ident** –
  A scalar, tuple, or dictionary representing the
  primary key.  For a composite (e.g. multiple column) primary key,
  a tuple or dictionary should be passed.
  For a single-column primary key, the scalar calling form is typically
  the most expedient.  If the primary key of a row is the value “5”,
  the call looks like:
  ```
  my_object = session.get(SomeClass, 5)
  ```
  The tuple form contains primary key values typically in
  the order in which they correspond to the mapped
  [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table)
  object’s primary key columns, or if the
  [Mapper.primary_key](https://docs.sqlalchemy.org/en/20/orm/mapping_api.html#sqlalchemy.orm.Mapper.params.primary_key) configuration parameter were
  used, in
  the order used for that parameter. For example, if the primary key
  of a row is represented by the integer
  digits “5, 10” the call would look like:
  ```
  my_object = session.get(SomeClass, (5, 10))
  ```
  The dictionary form should include as keys the mapped attribute names
  corresponding to each element of the primary key.  If the mapped class
  has the attributes `id`, `version_id` as the attributes which
  store the object’s primary key value, the call would look like:
  ```
  my_object = session.get(SomeClass, {"id": 5, "version_id": 10})
  ```
- **options** – optional sequence of loader options which will be
  applied to the query, if one is emitted.
- **populate_existing** – causes the method to unconditionally emit
  a SQL query and refresh the object with the newly loaded data,
  regardless of whether or not the object is already present.
- **with_for_update** – optional boolean `True` indicating FOR UPDATE
  should be used, or may be a dictionary containing flags to
  indicate a more specific set of FOR UPDATE flags for the SELECT;
  flags should match the parameters of
  [Query.with_for_update()](https://docs.sqlalchemy.org/en/20/orm/queryguide/query.html#sqlalchemy.orm.Query.with_for_update).
  Supersedes the [Session.refresh.lockmode](#sqlalchemy.orm.Session.refresh.params.lockmode) parameter.
- **execution_options** –
  optional dictionary of execution options,
  which will be associated with the query execution if one is emitted.
  This dictionary can provide a subset of the options that are
  accepted by [Connection.execution_options()](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection.execution_options), and may
  also provide additional options understood only in an ORM context.
  Added in version 1.4.29.
  See also
  [ORM Execution Options](https://docs.sqlalchemy.org/en/20/orm/queryguide/api.html#orm-queryguide-execution-options) - ORM-specific execution
  options
- **bind_arguments** –
  dictionary of additional arguments to determine
  the bind.  May include “mapper”, “bind”, or other custom arguments.
  Contents of this dictionary are passed to the
  [Session.get_bind()](#sqlalchemy.orm.Session.get_bind) method.

  Returns:

The object instance, or `None`.

      method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)get_bind(*mapper:_EntityBindKey[_O]|None=None*, ***, *clause:ClauseElement|None=None*, *bind:_SessionBind|None=None*, *_sa_skip_events:bool|None=None*, *_sa_skip_for_implicit_returning:bool=False*, ***kw:Any*) → [Engine](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Engine) | [Connection](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection)

Return a “bind” to which this [Session](#sqlalchemy.orm.Session) is bound.

The “bind” is usually an instance of [Engine](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Engine),
except in the case where the [Session](#sqlalchemy.orm.Session) has been
explicitly bound directly to a [Connection](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection).

For a multiply-bound or unbound [Session](#sqlalchemy.orm.Session), the
`mapper` or `clause` arguments are used to determine the
appropriate bind to return.

Note that the “mapper” argument is usually present
when [Session.get_bind()](#sqlalchemy.orm.Session.get_bind) is called via an ORM
operation such as a [Session.query()](#sqlalchemy.orm.Session.query), each
individual INSERT/UPDATE/DELETE operation within a
[Session.flush()](#sqlalchemy.orm.Session.flush), call, etc.

The order of resolution is:

1. if mapper given and [Session.binds](#sqlalchemy.orm.Session.params.binds) is present,
  locate a bind based first on the mapper in use, then
  on the mapped class in use, then on any base classes that are
  present in the `__mro__` of the mapped class, from more specific
  superclasses to more general.
2. if clause given and `Session.binds` is present,
  locate a bind based on [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) objects
  found in the given clause present in `Session.binds`.
3. if `Session.binds` is present, return that.
4. if clause given, attempt to return a bind
  linked to the [MetaData](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.MetaData) ultimately
  associated with the clause.
5. if mapper given, attempt to return a bind
  linked to the [MetaData](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.MetaData) ultimately
  associated with the [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) or other
  selectable to which the mapper is mapped.
6. No bind can be found, [UnboundExecutionError](https://docs.sqlalchemy.org/en/20/core/exceptions.html#sqlalchemy.exc.UnboundExecutionError)
  is raised.

Note that the [Session.get_bind()](#sqlalchemy.orm.Session.get_bind) method can be overridden on
a user-defined subclass of [Session](#sqlalchemy.orm.Session) to provide any kind
of bind resolution scheme.  See the example at
[Custom Vertical Partitioning](https://docs.sqlalchemy.org/en/20/orm/persistence_techniques.html#session-custom-partitioning).

  Parameters:

- **mapper** – Optional mapped class or corresponding [Mapper](https://docs.sqlalchemy.org/en/20/orm/mapping_api.html#sqlalchemy.orm.Mapper) instance.
  The bind can be derived from a [Mapper](https://docs.sqlalchemy.org/en/20/orm/mapping_api.html#sqlalchemy.orm.Mapper) first by
  consulting the “binds” map associated with this [Session](#sqlalchemy.orm.Session),
  and secondly by consulting the [MetaData](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.MetaData) associated
  with the [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) to which the [Mapper](https://docs.sqlalchemy.org/en/20/orm/mapping_api.html#sqlalchemy.orm.Mapper) is
  mapped for a bind.
- **clause** – A [ClauseElement](https://docs.sqlalchemy.org/en/20/core/foundation.html#sqlalchemy.sql.expression.ClauseElement) (i.e.
  [select()](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.select),
  [text()](https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text),
  etc.).  If the `mapper` argument is not present or could not
  produce a bind, the given expression construct will be searched
  for a bound element, typically a [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table)
  associated with
  bound [MetaData](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.MetaData).

See also

[Partitioning Strategies (e.g. multiple database backends per Session)](https://docs.sqlalchemy.org/en/20/orm/persistence_techniques.html#session-partitioning)

[Session.binds](#sqlalchemy.orm.Session.params.binds)

[Session.bind_mapper()](#sqlalchemy.orm.Session.bind_mapper)

[Session.bind_table()](#sqlalchemy.orm.Session.bind_table)

     method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)get_nested_transaction() → [SessionTransaction](#sqlalchemy.orm.SessionTransaction) | None

Return the current nested transaction in progress, if any.

Added in version 1.4.

     method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)get_one(*entity:_EntityBindKey[_O]*, *ident:_PKIdentityArgument*, ***, *options:Sequence[ORMOption]|None=None*, *populate_existing:bool=False*, *with_for_update:ForUpdateParameter=None*, *identity_token:Any|None=None*, *execution_options:OrmExecuteOptionsParameter={}*, *bind_arguments:_BindArguments|None=None*) → _O

Return exactly one instance based on the given primary key
identifier, or raise an exception if not found.

Raises [NoResultFound](https://docs.sqlalchemy.org/en/20/core/exceptions.html#sqlalchemy.exc.NoResultFound) if the query selects no rows.

For a detailed documentation of the arguments see the
method [Session.get()](#sqlalchemy.orm.Session.get).

Added in version 2.0.22.

   Returns:

The object instance.

See also

  [Session.get()](#sqlalchemy.orm.Session.get) - equivalent method that instead

returns `None` if no row was found with the provided primary
key

       method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)get_transaction() → [SessionTransaction](#sqlalchemy.orm.SessionTransaction) | None

Return the current root transaction in progress, if any.

Added in version 1.4.

     classmethod [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)identity_key(*class_:Type[Any]|None=None*, *ident:Any|Tuple[Any,...]=None*, ***, *instance:Any|None=None*, *row:Row[Any]|RowMapping|None=None*, *identity_token:Any|None=None*) → _IdentityKeyType[Any]

*inherited from the* `sqlalchemy.orm.session._SessionClassMethods.identity_key` *method of* `sqlalchemy.orm.session._SessionClassMethods`

Return an identity key.

This is an alias of [identity_key()](https://docs.sqlalchemy.org/en/20/orm/mapping_api.html#sqlalchemy.orm.util.identity_key).

    attribute [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)identity_map: [IdentityMap](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.IdentityMap)

A mapping of object identities to objects themselves.

Iterating through `Session.identity_map.values()` provides
access to the full set of persistent objects (i.e., those
that have row identity) currently in the session.

See also

[identity_key()](https://docs.sqlalchemy.org/en/20/orm/mapping_api.html#sqlalchemy.orm.util.identity_key) - helper function to produce the keys used
in this dictionary.

     method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)in_nested_transaction() → bool

Return True if this [Session](#sqlalchemy.orm.Session) has begun a nested
transaction, e.g. SAVEPOINT.

Added in version 1.4.

     method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)in_transaction() → bool

Return True if this [Session](#sqlalchemy.orm.Session) has begun a transaction.

Added in version 1.4.

See also

[Session.is_active](#sqlalchemy.orm.Session.is_active)

     attribute [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)info

A user-modifiable dictionary.

The initial value of this dictionary can be populated using the
`info` argument to the [Session](#sqlalchemy.orm.Session) constructor or
[sessionmaker](#sqlalchemy.orm.sessionmaker) constructor or factory methods.  The dictionary
here is always local to this [Session](#sqlalchemy.orm.Session) and can be modified
independently of all other [Session](#sqlalchemy.orm.Session) objects.

    method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)invalidate() → None

Close this Session, using connection invalidation.

This is a variant of [Session.close()](#sqlalchemy.orm.Session.close) that will additionally
ensure that the [Connection.invalidate()](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection.invalidate)
method will be called on each [Connection](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection) object
that is currently in use for a transaction (typically there is only
one connection unless the [Session](#sqlalchemy.orm.Session) is used with
multiple engines).

This can be called when the database is known to be in a state where
the connections are no longer safe to be used.

Below illustrates a scenario when using [gevent](https://www.gevent.org/), which can produce `Timeout` exceptions
that may mean the underlying connection should be discarded:

```
import gevent

try:
    sess = Session()
    sess.add(User())
    sess.commit()
except gevent.Timeout:
    sess.invalidate()
    raise
except:
    sess.rollback()
    raise
```

The method additionally does everything that [Session.close()](#sqlalchemy.orm.Session.close)
does, including that all ORM objects are expunged.

    property is_active: bool

True if this [Session](#sqlalchemy.orm.Session) not in “partial rollback” state.

Changed in version 1.4: The [Session](#sqlalchemy.orm.Session) no longer begins
a new transaction immediately, so this attribute will be False
when the [Session](#sqlalchemy.orm.Session) is first instantiated.

“partial rollback” state typically indicates that the flush process
of the [Session](#sqlalchemy.orm.Session) has failed, and that the
[Session.rollback()](#sqlalchemy.orm.Session.rollback) method must be emitted in order to
fully roll back the transaction.

If this [Session](#sqlalchemy.orm.Session) is not in a transaction at all, the
[Session](#sqlalchemy.orm.Session) will autobegin when it is first used, so in this
case [Session.is_active](#sqlalchemy.orm.Session.is_active) will return True.

Otherwise, if this [Session](#sqlalchemy.orm.Session) is within a transaction,
and that transaction has not been rolled back internally, the
[Session.is_active](#sqlalchemy.orm.Session.is_active) will also return True.

See also

[“This Session’s transaction has been rolled back due to a previous exception during flush.” (or similar)](https://docs.sqlalchemy.org/en/20/faq/sessions.html#faq-session-rollback)

[Session.in_transaction()](#sqlalchemy.orm.Session.in_transaction)

     method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)is_modified(*instance:object*, *include_collections:bool=True*) → bool

Return `True` if the given instance has locally
modified attributes.

This method retrieves the history for each instrumented
attribute on the instance and performs a comparison of the current
value to its previously flushed or committed value, if any.

It is in effect a more expensive and accurate
version of checking for the given instance in the
[Session.dirty](#sqlalchemy.orm.Session.dirty) collection; a full test for
each attribute’s net “dirty” status is performed.

E.g.:

```
return session.is_modified(someobject)
```

A few caveats to this method apply:

- Instances present in the [Session.dirty](#sqlalchemy.orm.Session.dirty) collection may
  report `False` when tested with this method.  This is because
  the object may have received change events via attribute mutation,
  thus placing it in [Session.dirty](#sqlalchemy.orm.Session.dirty), but ultimately the state
  is the same as that loaded from the database, resulting in no net
  change here.
- Scalar attributes may not have recorded the previously set
  value when a new value was applied, if the attribute was not loaded,
  or was expired, at the time the new value was received - in these
  cases, the attribute is assumed to have a change, even if there is
  ultimately no net change against its database value. SQLAlchemy in
  most cases does not need the “old” value when a set event occurs, so
  it skips the expense of a SQL call if the old value isn’t present,
  based on the assumption that an UPDATE of the scalar value is
  usually needed, and in those few cases where it isn’t, is less
  expensive on average than issuing a defensive SELECT.
  The “old” value is fetched unconditionally upon set only if the
  attribute container has the `active_history` flag set to `True`.
  This flag is set typically for primary key attributes and scalar
  object references that are not a simple many-to-one.  To set this
  flag for any arbitrary mapped column, use the `active_history`
  argument with [column_property()](https://docs.sqlalchemy.org/en/20/orm/mapping_api.html#sqlalchemy.orm.column_property).

  Parameters:

- **instance** – mapped instance to be tested for pending changes.
- **include_collections** – Indicates if multivalued collections
  should be included in the operation.  Setting this to `False` is a
  way to detect only local-column based properties (i.e. scalar columns
  or many-to-one foreign keys) that would result in an UPDATE for this
  instance upon flush.

      method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)merge(*instance:_O*, ***, *load:bool=True*, *options:Sequence[ORMOption]|None=None*) → _O

Copy the state of a given instance into a corresponding instance
within this [Session](#sqlalchemy.orm.Session).

[Session.merge()](#sqlalchemy.orm.Session.merge) examines the primary key attributes of the
source instance, and attempts to reconcile it with an instance of the
same primary key in the session.   If not found locally, it attempts
to load the object from the database based on primary key, and if
none can be located, creates a new instance.  The state of each
attribute on the source instance is then copied to the target
instance.  The resulting target instance is then returned by the
method; the original source instance is left unmodified, and
un-associated with the [Session](#sqlalchemy.orm.Session) if not already.

This operation cascades to associated instances if the association is
mapped with `cascade="merge"`.

See [Merging](https://docs.sqlalchemy.org/en/20/orm/session_state_management.html#unitofwork-merging) for a detailed discussion of merging.

  Parameters:

- **instance** – Instance to be merged.
- **load** –
  Boolean, when False, [merge()](#sqlalchemy.orm.Session.merge) switches into
  a “high performance” mode which causes it to forego emitting history
  events as well as all database access.  This flag is used for
  cases such as transferring graphs of objects into a [Session](#sqlalchemy.orm.Session)
  from a second level cache, or to transfer just-loaded objects
  into the [Session](#sqlalchemy.orm.Session) owned by a worker thread or process
  without re-querying the database.
  The `load=False` use case adds the caveat that the given
  object has to be in a “clean” state, that is, has no pending changes
  to be flushed - even if the incoming object is detached from any
  [Session](#sqlalchemy.orm.Session).   This is so that when
  the merge operation populates local attributes and
  cascades to related objects and
  collections, the values can be “stamped” onto the
  target object as is, without generating any history or attribute
  events, and without the need to reconcile the incoming data with
  any existing related objects or collections that might not
  be loaded.  The resulting objects from `load=False` are always
  produced as “clean”, so it is only appropriate that the given objects
  should be “clean” as well, else this suggests a mis-use of the
  method.
- **options** –
  optional sequence of loader options which will be
  applied to the [Session.get()](#sqlalchemy.orm.Session.get) method when the merge
  operation loads the existing version of the object from the database.
  Added in version 1.4.24.

See also

[make_transient_to_detached()](#sqlalchemy.orm.make_transient_to_detached) - provides for an alternative
means of “merging” a single object into the [Session](#sqlalchemy.orm.Session)

     property new: IdentitySet

The set of all instances marked as ‘new’ within this `Session`.

    attribute [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)no_autoflush

Return a context manager that disables autoflush.

e.g.:

```
with session.no_autoflush:

    some_object = SomeClass()
    session.add(some_object)
    # won't autoflush
    some_object.related_thing = session.query(SomeRelated).first()
```

Operations that proceed within the `with:` block
will not be subject to flushes occurring upon query
access.  This is useful when initializing a series
of objects which involve existing database queries,
where the uncompleted object should not yet be flushed.

    classmethod [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)object_session(*instance:object*) → [Session](#sqlalchemy.orm.Session) | None

*inherited from the* `sqlalchemy.orm.session._SessionClassMethods.object_session` *method of* `sqlalchemy.orm.session._SessionClassMethods`

Return the [Session](#sqlalchemy.orm.Session) to which an object belongs.

This is an alias of [object_session()](#sqlalchemy.orm.object_session).

    method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)prepare() → None

Prepare the current transaction in progress for two phase commit.

If no transaction is in progress, this method raises an
[InvalidRequestError](https://docs.sqlalchemy.org/en/20/core/exceptions.html#sqlalchemy.exc.InvalidRequestError).

Only root transactions of two phase sessions can be prepared. If the
current transaction is not such, an
[InvalidRequestError](https://docs.sqlalchemy.org/en/20/core/exceptions.html#sqlalchemy.exc.InvalidRequestError) is raised.

    method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)query(**entities:_ColumnsClauseArgument[Any]*, ***kwargs:Any*) → [Query](https://docs.sqlalchemy.org/en/20/orm/queryguide/query.html#sqlalchemy.orm.Query)[Any]

Return a new [Query](https://docs.sqlalchemy.org/en/20/orm/queryguide/query.html#sqlalchemy.orm.Query) object corresponding to this
[Session](#sqlalchemy.orm.Session).

Note that the [Query](https://docs.sqlalchemy.org/en/20/orm/queryguide/query.html#sqlalchemy.orm.Query) object is legacy as of
SQLAlchemy 2.0; the [select()](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.select) construct is now used
to construct ORM queries.

See also

[SQLAlchemy Unified Tutorial](https://docs.sqlalchemy.org/en/20/tutorial/index.html#unified-tutorial)

[ORM Querying Guide](https://docs.sqlalchemy.org/en/20/orm/queryguide/index.html)

[Legacy Query API](https://docs.sqlalchemy.org/en/20/orm/queryguide/query.html) - legacy API doc

     method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)refresh(*instance:object*, *attribute_names:Iterable[str]|None=None*, *with_for_update:ForUpdateParameter=None*) → None

Expire and refresh attributes on the given instance.

The selected attributes will first be expired as they would when using
[Session.expire()](#sqlalchemy.orm.Session.expire); then a SELECT statement will be issued to
the database to refresh column-oriented attributes with the current
value available in the current transaction.

[relationship()](https://docs.sqlalchemy.org/en/20/orm/relationship_api.html#sqlalchemy.orm.relationship) oriented attributes will also be immediately
loaded if they were already eagerly loaded on the object, using the
same eager loading strategy that they were loaded with originally.

Added in version 1.4: - the [Session.refresh()](#sqlalchemy.orm.Session.refresh) method
can also refresh eagerly loaded attributes.

[relationship()](https://docs.sqlalchemy.org/en/20/orm/relationship_api.html#sqlalchemy.orm.relationship) oriented attributes that would normally
load using the `select` (or “lazy”) loader strategy will also
load **if they are named explicitly in the attribute_names
collection**, emitting a SELECT statement for the attribute using the
`immediate` loader strategy.  If lazy-loaded relationships are not
named in [Session.refresh.attribute_names](#sqlalchemy.orm.Session.refresh.params.attribute_names), then
they remain as “lazy loaded” attributes and are not implicitly
refreshed.

Changed in version 2.0.4: The [Session.refresh()](#sqlalchemy.orm.Session.refresh) method
will now refresh lazy-loaded [relationship()](https://docs.sqlalchemy.org/en/20/orm/relationship_api.html#sqlalchemy.orm.relationship) oriented
attributes for those which are named explicitly in the
[Session.refresh.attribute_names](#sqlalchemy.orm.Session.refresh.params.attribute_names) collection.

Tip

While the [Session.refresh()](#sqlalchemy.orm.Session.refresh) method is capable of
refreshing both column and relationship oriented attributes, its
primary focus is on refreshing of local column-oriented attributes
on a single instance. For more open ended “refresh” functionality,
including the ability to refresh the attributes on many objects at
once while having explicit control over relationship loader
strategies, use the
[populate existing](https://docs.sqlalchemy.org/en/20/orm/queryguide/api.html#orm-queryguide-populate-existing) feature
instead.

Note that a highly isolated transaction will return the same values as
were previously read in that same transaction, regardless of changes
in database state outside of that transaction.   Refreshing
attributes usually only makes sense at the start of a transaction
where database rows have not yet been accessed.

  Parameters:

- **attribute_names** – optional.  An iterable collection of
  string attribute names indicating a subset of attributes to
  be refreshed.
- **with_for_update** – optional boolean `True` indicating FOR UPDATE
  should be used, or may be a dictionary containing flags to
  indicate a more specific set of FOR UPDATE flags for the SELECT;
  flags should match the parameters of
  [Query.with_for_update()](https://docs.sqlalchemy.org/en/20/orm/queryguide/query.html#sqlalchemy.orm.Query.with_for_update).
  Supersedes the [Session.refresh.lockmode](#sqlalchemy.orm.Session.refresh.params.lockmode) parameter.

See also

[Refreshing / Expiring](https://docs.sqlalchemy.org/en/20/orm/session_state_management.html#session-expire) - introductory material

[Session.expire()](#sqlalchemy.orm.Session.expire)

[Session.expire_all()](#sqlalchemy.orm.Session.expire_all)

[Populate Existing](https://docs.sqlalchemy.org/en/20/orm/queryguide/api.html#orm-queryguide-populate-existing) - allows any ORM query
to refresh objects as they would be loaded normally.

     method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)reset() → None

Close out the transactional resources and ORM objects used by this
[Session](#sqlalchemy.orm.Session), resetting the session to its initial state.

This method provides for same “reset-only” behavior that the
[Session.close()](#sqlalchemy.orm.Session.close) method has provided historically, where the
state of the [Session](#sqlalchemy.orm.Session) is reset as though the object were
brand new, and ready to be used again.
This method may then be useful for [Session](#sqlalchemy.orm.Session) objects
which set [Session.close_resets_only](#sqlalchemy.orm.Session.params.close_resets_only) to `False`,
so that “reset only” behavior is still available.

Added in version 2.0.22.

See also

[Closing](https://docs.sqlalchemy.org/en/20/orm/session_basics.html#session-closing) - detail on the semantics of
[Session.close()](#sqlalchemy.orm.Session.close) and [Session.reset()](#sqlalchemy.orm.Session.reset).

[Session.close()](#sqlalchemy.orm.Session.close) - a similar method will additionally
prevent reuse of the Session when the parameter
[Session.close_resets_only](#sqlalchemy.orm.Session.params.close_resets_only) is set to `False`.

     method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)rollback() → None

Rollback the current transaction in progress.

If no transaction is in progress, this method is a pass-through.

The method always rolls back
the topmost database transaction, discarding any nested
transactions that may be in progress.

See also

[Rolling Back](https://docs.sqlalchemy.org/en/20/orm/session_basics.html#session-rollback)

[Managing Transactions](https://docs.sqlalchemy.org/en/20/orm/session_transaction.html#unitofwork-transaction)

     method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)scalar(*statement:Executable*, *params:_CoreSingleExecuteParams|None=None*, ***, *execution_options:OrmExecuteOptionsParameter={}*, *bind_arguments:_BindArguments|None=None*, ***kw:Any*) → Any

Execute a statement and return a scalar result.

Usage and parameters are the same as that of
[Session.execute()](#sqlalchemy.orm.Session.execute); the return result is a scalar Python
value.

    method [sqlalchemy.orm.Session.](#sqlalchemy.orm.Session)scalars(*statement:Executable*, *params:_CoreAnyExecuteParams|None=None*, ***, *execution_options:OrmExecuteOptionsParameter={}*, *bind_arguments:_BindArguments|None=None*, ***kw:Any*) → [ScalarResult](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.ScalarResult)[Any]

Execute a statement and return the results as scalars.

Usage and parameters are the same as that of
[Session.execute()](#sqlalchemy.orm.Session.execute); the return result is a
[ScalarResult](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.ScalarResult) filtering object which
will return single elements rather than [Row](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Row) objects.

  Returns:

a [ScalarResult](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.ScalarResult) object

Added in version 1.4.24: Added [Session.scalars()](#sqlalchemy.orm.Session.scalars)

Added in version 1.4.26: Added [scoped_session.scalars()](https://docs.sqlalchemy.org/en/20/orm/contextual.html#sqlalchemy.orm.scoped_session.scalars)

See also

[Selecting ORM Entities](https://docs.sqlalchemy.org/en/20/orm/queryguide/select.html#orm-queryguide-select-orm-entities) - contrasts the behavior
of [Session.execute()](#sqlalchemy.orm.Session.execute) to [Session.scalars()](#sqlalchemy.orm.Session.scalars)

      class sqlalchemy.orm.SessionTransaction

*inherits from* `sqlalchemy.orm.state_changes._StateChange`, `sqlalchemy.engine.util.TransactionalContext`

A [Session](#sqlalchemy.orm.Session)-level transaction.

[SessionTransaction](#sqlalchemy.orm.SessionTransaction) is produced from the
[Session.begin()](#sqlalchemy.orm.Session.begin)
and [Session.begin_nested()](#sqlalchemy.orm.Session.begin_nested) methods.   It’s largely an internal
object that in modern use provides a context manager for session
transactions.

Documentation on interacting with [SessionTransaction](#sqlalchemy.orm.SessionTransaction) is
at: [Managing Transactions](https://docs.sqlalchemy.org/en/20/orm/session_transaction.html#unitofwork-transaction).

Changed in version 1.4: The scoping and API methods to work with the
[SessionTransaction](#sqlalchemy.orm.SessionTransaction) object directly have been simplified.

See also

[Managing Transactions](https://docs.sqlalchemy.org/en/20/orm/session_transaction.html#unitofwork-transaction)

[Session.begin()](#sqlalchemy.orm.Session.begin)

[Session.begin_nested()](#sqlalchemy.orm.Session.begin_nested)

[Session.rollback()](#sqlalchemy.orm.Session.rollback)

[Session.commit()](#sqlalchemy.orm.Session.commit)

[Session.in_transaction()](#sqlalchemy.orm.Session.in_transaction)

[Session.in_nested_transaction()](#sqlalchemy.orm.Session.in_nested_transaction)

[Session.get_transaction()](#sqlalchemy.orm.Session.get_transaction)

[Session.get_nested_transaction()](#sqlalchemy.orm.Session.get_nested_transaction)

| Member Name | Description |
| --- | --- |
| nested | Indicates if this is a nested, or SAVEPOINT, transaction. |
| origin | Origin of thisSessionTransaction. |

   attribute [sqlalchemy.orm.SessionTransaction.](#sqlalchemy.orm.SessionTransaction)nested: bool = False

Indicates if this is a nested, or SAVEPOINT, transaction.

When [SessionTransaction.nested](#sqlalchemy.orm.SessionTransaction.nested) is True, it is expected
that [SessionTransaction.parent](#sqlalchemy.orm.SessionTransaction.parent) will be present as well,
linking to the enclosing [SessionTransaction](#sqlalchemy.orm.SessionTransaction).

See also

[SessionTransaction.origin](#sqlalchemy.orm.SessionTransaction.origin)

     attribute [sqlalchemy.orm.SessionTransaction.](#sqlalchemy.orm.SessionTransaction)origin: [SessionTransactionOrigin](#sqlalchemy.orm.SessionTransactionOrigin)

Origin of this [SessionTransaction](#sqlalchemy.orm.SessionTransaction).

Refers to a [SessionTransactionOrigin](#sqlalchemy.orm.SessionTransactionOrigin) instance which is an
enumeration indicating the source event that led to constructing
this [SessionTransaction](#sqlalchemy.orm.SessionTransaction).

Added in version 2.0.

     property parent: [SessionTransaction](#sqlalchemy.orm.SessionTransaction) | None

The parent [SessionTransaction](#sqlalchemy.orm.SessionTransaction) of this
[SessionTransaction](#sqlalchemy.orm.SessionTransaction).

If this attribute is `None`, indicates this
[SessionTransaction](#sqlalchemy.orm.SessionTransaction) is at the top of the stack, and
corresponds to a real “COMMIT”/”ROLLBACK”
block.  If non-`None`, then this is either a “subtransaction”
(an internal marker object used by the flush process) or a
“nested” / SAVEPOINT transaction.  If the
[SessionTransaction.nested](#sqlalchemy.orm.SessionTransaction.nested) attribute is `True`, then
this is a SAVEPOINT, and if `False`, indicates this a subtransaction.

     class sqlalchemy.orm.SessionTransactionOrigin

*inherits from* `enum.Enum`

indicates the origin of a [SessionTransaction](#sqlalchemy.orm.SessionTransaction).

This enumeration is present on the
[SessionTransaction.origin](#sqlalchemy.orm.SessionTransaction.origin) attribute of any
[SessionTransaction](#sqlalchemy.orm.SessionTransaction) object.

Added in version 2.0.

| Member Name | Description |
| --- | --- |
| AUTOBEGIN | transaction were started by autobegin |
| BEGIN | transaction were started by callingSession.begin() |
| BEGIN_NESTED | transaction were started bySession.begin_nested() |
| SUBTRANSACTION | transaction is an internal “subtransaction” |

   attribute [sqlalchemy.orm.SessionTransactionOrigin.](#sqlalchemy.orm.SessionTransactionOrigin)AUTOBEGIN = 0

transaction were started by autobegin

    attribute [sqlalchemy.orm.SessionTransactionOrigin.](#sqlalchemy.orm.SessionTransactionOrigin)BEGIN = 1

transaction were started by calling [Session.begin()](#sqlalchemy.orm.Session.begin)

    attribute [sqlalchemy.orm.SessionTransactionOrigin.](#sqlalchemy.orm.SessionTransactionOrigin)BEGIN_NESTED = 2

transaction were started by [Session.begin_nested()](#sqlalchemy.orm.Session.begin_nested)

    attribute [sqlalchemy.orm.SessionTransactionOrigin.](#sqlalchemy.orm.SessionTransactionOrigin)SUBTRANSACTION = 3

transaction is an internal “subtransaction”

## Session Utilities

| Object Name | Description |
| --- | --- |
| close_all_sessions() | Close all sessions in memory. |
| make_transient(instance) | Alter the state of the given instance so that it istransient. |
| make_transient_to_detached(instance) | Make the given transient instancedetached. |
| object_session(instance) | Return theSessionto which the given instance belongs. |
| was_deleted(object_) | Return True if the given object was deleted
within a session flush. |

   function sqlalchemy.orm.close_all_sessions() → None

Close all sessions in memory.

This function consults a global registry of all [Session](#sqlalchemy.orm.Session) objects
and calls [Session.close()](#sqlalchemy.orm.Session.close) on them, which resets them to a clean
state.

This function is not for general use but may be useful for test suites
within the teardown scheme.

Added in version 1.3.

     function sqlalchemy.orm.make_transient(*instance:object*) → None

Alter the state of the given instance so that it is [transient](https://docs.sqlalchemy.org/en/20/glossary.html#term-transient).

Note

[make_transient()](#sqlalchemy.orm.make_transient) is a special-case function for
advanced use cases only.

The given mapped instance is assumed to be in the [persistent](https://docs.sqlalchemy.org/en/20/glossary.html#term-persistent) or
[detached](https://docs.sqlalchemy.org/en/20/glossary.html#term-detached) state.   The function will remove its association with any
[Session](#sqlalchemy.orm.Session) as well as its [InstanceState.identity](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.InstanceState.identity). The
effect is that the object will behave as though it were newly constructed,
except retaining any attribute / collection values that were loaded at the
time of the call.   The [InstanceState.deleted](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.InstanceState.deleted) flag is also reset
if this object had been deleted as a result of using
[Session.delete()](#sqlalchemy.orm.Session.delete).

Warning

[make_transient()](#sqlalchemy.orm.make_transient) does **not** “unexpire” or otherwise eagerly
load ORM-mapped attributes that are not currently loaded at the time
the function is called.   This includes attributes which:

- were expired via [Session.expire()](#sqlalchemy.orm.Session.expire)
- were expired as the natural effect of committing a session
  transaction, e.g. [Session.commit()](#sqlalchemy.orm.Session.commit)
- are normally [lazy loaded](https://docs.sqlalchemy.org/en/20/glossary.html#term-lazy-loaded) but are not currently loaded
- are “deferred” (see [Limiting which Columns Load with Column Deferral](https://docs.sqlalchemy.org/en/20/orm/queryguide/columns.html#orm-queryguide-column-deferral)) and are
  not yet loaded
- were not present in the query which loaded this object, such as that
  which is common in joined table inheritance and other scenarios.

After [make_transient()](#sqlalchemy.orm.make_transient) is called, unloaded attributes such
as those above will normally resolve to the value `None` when
accessed, or an empty collection for a collection-oriented attribute.
As the object is transient and un-associated with any database
identity, it will no longer retrieve these values.

See also

[make_transient_to_detached()](#sqlalchemy.orm.make_transient_to_detached)

     function sqlalchemy.orm.make_transient_to_detached(*instance:object*) → None

Make the given transient instance [detached](https://docs.sqlalchemy.org/en/20/glossary.html#term-detached).

Note

[make_transient_to_detached()](#sqlalchemy.orm.make_transient_to_detached) is a special-case function for
advanced use cases only.

All attribute history on the given instance
will be reset as though the instance were freshly loaded
from a query.  Missing attributes will be marked as expired.
The primary key attributes of the object, which are required, will be made
into the “key” of the instance.

The object can then be added to a session, or merged
possibly with the load=False flag, at which point it will look
as if it were loaded that way, without emitting SQL.

This is a special use case function that differs from a normal
call to [Session.merge()](#sqlalchemy.orm.Session.merge) in that a given persistent state
can be manufactured without any SQL calls.

See also

[make_transient()](#sqlalchemy.orm.make_transient)

[Session.enable_relationship_loading()](#sqlalchemy.orm.Session.enable_relationship_loading)

     function sqlalchemy.orm.object_session(*instance:object*) → [Session](#sqlalchemy.orm.Session) | None

Return the [Session](#sqlalchemy.orm.Session) to which the given instance belongs.

This is essentially the same as the [InstanceState.session](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.InstanceState.session)
accessor.  See that attribute for details.

    function sqlalchemy.orm.util.was_deleted(*object_:object*) → bool

Return True if the given object was deleted
within a session flush.

This is regardless of whether or not the object is
persistent or detached.

See also

[InstanceState.was_deleted](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.InstanceState.was_deleted)

## Attribute and State Management Utilities

These functions are provided by the SQLAlchemy attribute
instrumentation API to provide a detailed interface for dealing
with instances, attribute values, and history.  Some of them
are useful when constructing event listener functions, such as
those described in [ORM Events](https://docs.sqlalchemy.org/en/20/orm/events.html).

| Object Name | Description |
| --- | --- |
| del_attribute(instance, key) | Delete the value of an attribute, firing history events. |
| flag_dirty(instance) | Mark an instance as ‘dirty’ without any specific attribute mentioned. |
| flag_modified(instance, key) | Mark an attribute on an instance as ‘modified’. |
| get_attribute(instance, key) | Get the value of an attribute, firing any callables required. |
| get_history(obj, key[, passive]) | Return aHistoryrecord for the given object
and attribute key. |
| History | A 3-tuple of added, unchanged and deleted values,
representing the changes which have occurred on an instrumented
attribute. |
| init_collection(obj, key) | Initialize a collection attribute and return the collection adapter. |
| instance_state | Return theInstanceStatefor a given
mapped object. |
| is_instrumented(instance, key) | Return True if the given attribute on the given instance is
instrumented by the attributes package. |
| object_state(instance) | Given an object, return theInstanceStateassociated with the object. |
| set_attribute(instance, key, value[, initiator]) | Set the value of an attribute, firing history events. |
| set_committed_value(instance, key, value) | Set the value of an attribute with no history events. |

   function sqlalchemy.orm.util.object_state(*instance:_T*) → [InstanceState](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.InstanceState)[_T]

Given an object, return the [InstanceState](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.InstanceState)
associated with the object.

Raises [sqlalchemy.orm.exc.UnmappedInstanceError](https://docs.sqlalchemy.org/en/20/orm/exceptions.html#sqlalchemy.orm.exc.UnmappedInstanceError)
if no mapping is configured.

Equivalent functionality is available via the [inspect()](https://docs.sqlalchemy.org/en/20/core/inspection.html#sqlalchemy.inspect)
function as:

```
inspect(instance)
```

Using the inspection system will raise
[sqlalchemy.exc.NoInspectionAvailable](https://docs.sqlalchemy.org/en/20/core/exceptions.html#sqlalchemy.exc.NoInspectionAvailable) if the instance is
not part of a mapping.

    function sqlalchemy.orm.attributes.del_attribute(*instance:object*, *key:str*) → None

Delete the value of an attribute, firing history events.

This function may be used regardless of instrumentation
applied directly to the class, i.e. no descriptors are required.
Custom attribute management schemes will need to make usage
of this method to establish attribute state as understood
by SQLAlchemy.

    function sqlalchemy.orm.attributes.get_attribute(*instance:object*, *key:str*) → Any

Get the value of an attribute, firing any callables required.

This function may be used regardless of instrumentation
applied directly to the class, i.e. no descriptors are required.
Custom attribute management schemes will need to make usage
of this method to make usage of attribute state as understood
by SQLAlchemy.

    function sqlalchemy.orm.attributes.get_history(*obj:object*, *key:str*, *passive:PassiveFlag=symbol('PASSIVE_OFF')*) → [History](#sqlalchemy.orm.attributes.History)

Return a [History](#sqlalchemy.orm.attributes.History) record for the given object
and attribute key.

This is the **pre-flush** history for a given attribute, which is
reset each time the [Session](#sqlalchemy.orm.Session) flushes changes to the
current database transaction.

Note

Prefer to use the [AttributeState.history](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.AttributeState.history) and
[AttributeState.load_history()](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.AttributeState.load_history) accessors to retrieve the
[History](#sqlalchemy.orm.attributes.History) for instance attributes.

   Parameters:

- **obj** – an object whose class is instrumented by the
  attributes package.
- **key** – string attribute name.
- **passive** – indicates loading behavior for the attribute
  if the value is not already present.   This is a
  bitflag attribute, which defaults to the symbol
  `PASSIVE_OFF` indicating all necessary SQL
  should be emitted.

See also

[AttributeState.history](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.AttributeState.history)

[AttributeState.load_history()](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.AttributeState.load_history) - retrieve history
using loader callables if the value is not locally present.

     function sqlalchemy.orm.attributes.init_collection(*obj:object*, *key:str*) → [CollectionAdapter](https://docs.sqlalchemy.org/en/20/orm/collection_api.html#sqlalchemy.orm.collections.CollectionAdapter)

Initialize a collection attribute and return the collection adapter.

This function is used to provide direct access to collection internals
for a previously unloaded attribute.  e.g.:

```
collection_adapter = init_collection(someobject, "elements")
for elem in values:
    collection_adapter.append_without_event(elem)
```

For an easier way to do the above, see
[set_committed_value()](#sqlalchemy.orm.attributes.set_committed_value).

  Parameters:

- **obj** – a mapped object
- **key** – string attribute name where the collection is located.

      function sqlalchemy.orm.attributes.flag_modified(*instance:object*, *key:str*) → None

Mark an attribute on an instance as ‘modified’.

This sets the ‘modified’ flag on the instance and
establishes an unconditional change event for the given attribute.
The attribute must have a value present, else an
[InvalidRequestError](https://docs.sqlalchemy.org/en/20/core/exceptions.html#sqlalchemy.exc.InvalidRequestError) is raised.

To mark an object “dirty” without referring to any specific attribute
so that it is considered within a flush, use the
[flag_dirty()](#sqlalchemy.orm.attributes.flag_dirty) call.

See also

[flag_dirty()](#sqlalchemy.orm.attributes.flag_dirty)

     function sqlalchemy.orm.attributes.flag_dirty(*instance:object*) → None

Mark an instance as ‘dirty’ without any specific attribute mentioned.

This is a special operation that will allow the object to travel through
the flush process for interception by events such as
[SessionEvents.before_flush()](https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.SessionEvents.before_flush).   Note that no SQL will be emitted in
the flush process for an object that has no changes, even if marked dirty
via this method.  However, a [SessionEvents.before_flush()](https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.SessionEvents.before_flush) handler
will be able to see the object in the [Session.dirty](#sqlalchemy.orm.Session.dirty) collection and
may establish changes on it, which will then be included in the SQL
emitted.

Added in version 1.2.

See also

[flag_modified()](#sqlalchemy.orm.attributes.flag_modified)

     function sqlalchemy.orm.attributes.instance_state()

Return the [InstanceState](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.InstanceState) for a given
mapped object.

This function is the internal version
of [object_state()](#sqlalchemy.orm.util.object_state).   The
[object_state()](#sqlalchemy.orm.util.object_state) and/or the
[inspect()](https://docs.sqlalchemy.org/en/20/core/inspection.html#sqlalchemy.inspect) function is preferred here
as they each emit an informative exception
if the given object is not mapped.

    function sqlalchemy.orm.instrumentation.is_instrumented(*instance*, *key*)

Return True if the given attribute on the given instance is
instrumented by the attributes package.

This function may be used regardless of instrumentation
applied directly to the class, i.e. no descriptors are required.

    function sqlalchemy.orm.attributes.set_attribute(*instance:object*, *key:str*, *value:Any*, *initiator:AttributeEventToken|None=None*) → None

Set the value of an attribute, firing history events.

This function may be used regardless of instrumentation
applied directly to the class, i.e. no descriptors are required.
Custom attribute management schemes will need to make usage
of this method to establish attribute state as understood
by SQLAlchemy.

  Parameters:

- **instance** – the object that will be modified
- **key** – string name of the attribute
- **value** – value to assign
- **initiator** –
  an instance of `Event` that would have
  been propagated from a previous event listener.  This argument
  is used when the [set_attribute()](#sqlalchemy.orm.attributes.set_attribute) function is being used within
  an existing event listening function where an `Event` object
  is being supplied; the object may be used to track the origin of the
  chain of events.
  Added in version 1.2.3.

      function sqlalchemy.orm.attributes.set_committed_value(*instance:object*, *key:str*, *value:Any*) → None

Set the value of an attribute with no history events.

Cancels any previous history present.  The value should be
a scalar value for scalar-holding attributes, or
an iterable for any collection-holding attribute.

This is the same underlying method used when a lazy loader
fires off and loads additional data from the database.
In particular, this method can be used by application code
which has loaded additional attributes or collections through
separate queries, which can then be attached to an instance
as though it were part of its original loaded state.

    class sqlalchemy.orm.attributes.History

*inherits from* `builtins.tuple`

A 3-tuple of added, unchanged and deleted values,
representing the changes which have occurred on an instrumented
attribute.

The easiest way to get a [History](#sqlalchemy.orm.attributes.History) object for a particular
attribute on an object is to use the [inspect()](https://docs.sqlalchemy.org/en/20/core/inspection.html#sqlalchemy.inspect) function:

```
from sqlalchemy import inspect

hist = inspect(myobject).attrs.myattribute.history
```

Each tuple member is an iterable sequence:

- `added` - the collection of items added to the attribute (the first
  tuple element).
- `unchanged` - the collection of items that have not changed on the
  attribute (the second tuple element).
- `deleted` - the collection of items that have been removed from the
  attribute (the third tuple element).

| Member Name | Description |
| --- | --- |
| added | Alias for field number 0 |
| deleted | Alias for field number 2 |
| empty() | Return True if thisHistoryhas no changes
and no existing, unchanged state. |
| has_changes() | Return True if thisHistoryhas changes. |
| non_added() | Return a collection of unchanged + deleted. |
| non_deleted() | Return a collection of added + unchanged. |
| sum() | Return a collection of added + unchanged + deleted. |
| unchanged | Alias for field number 1 |

   attribute [sqlalchemy.orm.attributes.History.](#sqlalchemy.orm.attributes.History)added: Tuple | List[Any]

Alias for field number 0

    attribute [sqlalchemy.orm.attributes.History.](#sqlalchemy.orm.attributes.History)deleted: Tuple | List[Any]

Alias for field number 2

    method [sqlalchemy.orm.attributes.History.](#sqlalchemy.orm.attributes.History)empty() → bool

Return True if this [History](#sqlalchemy.orm.attributes.History) has no changes
and no existing, unchanged state.

    method [sqlalchemy.orm.attributes.History.](#sqlalchemy.orm.attributes.History)has_changes() → bool

Return True if this [History](#sqlalchemy.orm.attributes.History) has changes.

    method [sqlalchemy.orm.attributes.History.](#sqlalchemy.orm.attributes.History)non_added() → Sequence[Any]

Return a collection of unchanged + deleted.

    method [sqlalchemy.orm.attributes.History.](#sqlalchemy.orm.attributes.History)non_deleted() → Sequence[Any]

Return a collection of added + unchanged.

    method [sqlalchemy.orm.attributes.History.](#sqlalchemy.orm.attributes.History)sum() → Sequence[Any]

Return a collection of added + unchanged + deleted.

    attribute [sqlalchemy.orm.attributes.History.](#sqlalchemy.orm.attributes.History)unchanged: Tuple | List[Any]

Alias for field number 1
