# SQLAlchemy 2.0 Documentation

# SQLAlchemy 2.0 Documentation

# Class Mapping API

| Object Name | Description |
| --- | --- |
| add_mapped_attribute(target, key, attr) | Add a new mapped attribute to an ORM mapped class. |
| as_declarative(**kw) | Class decorator which will adapt a given class into adeclarative_base(). |
| class_mapper(class_[, configure]) | Given a class, return the primaryMapperassociated
with the key. |
| clear_mappers() | Remove all mappers from all classes. |
| column_property(column, *additional_columns, [group, deferred, raiseload, comparator_factory, init, repr, default, default_factory, compare, kw_only, hash, active_history, expire_on_flush, info, doc, dataclass_metadata]) | Provide a column-level property for use with a mapping. |
| configure_mappers() | Initialize the inter-mapper relationships of all mappers that
have been constructed thus far across allregistrycollections. |
| declarative_base(*, [metadata, mapper, cls, name, class_registry, type_annotation_map, constructor, metaclass]) | Construct a base class for declarative class definitions. |
| declarative_mixin(cls) | Mark a class as providing the feature of “declarative mixin”. |
| DeclarativeBase | Base class used for declarative class definitions. |
| DeclarativeBaseNoMeta | Same asDeclarativeBase, but does not use a metaclass
to intercept new attributes. |
| declared_attr | Mark a class-level method as representing the definition of
a mapped property or Declarative directive. |
| has_inherited_table(cls) | Given a class, return True if any of the classes it inherits from has a
mapped table, otherwise return False. |
| identity_key([class_, ident], *, [instance, row, identity_token]) | Generate “identity key” tuples, as are used as keys in theSession.identity_mapdictionary. |
| mapped_as_dataclass(registry, *, [init, repr, eq, order, unsafe_hash, match_args, kw_only, dataclass_callable]) | Standalone function form ofregistry.mapped_as_dataclass()which may have better compatibility with mypy. |
| mapped_column([__name_pos, __type_pos], *args, [init, repr, default, default_factory, compare, kw_only, hash, nullable, primary_key, deferred, deferred_group, deferred_raiseload, use_existing_column, name, type_, autoincrement, doc, key, index, unique, info, onupdate, insert_default, server_default, server_onupdate, active_history, quote, system, comment, sort_order, dataclass_metadata], **kw) | declare a new ORM-mappedColumnconstruct
for use withinDeclarative Tableconfiguration. |
| MappedAsDataclass | Mixin class to indicate when mapping this class, also convert it to be
a dataclass. |
| MappedClassProtocol | A protocol representing a SQLAlchemy mapped class. |
| Mapper | Defines an association between a Python class and a database table or
other relational structure, so that ORM operations against the class may
proceed. |
| object_mapper(instance) | Given an object, return the primary Mapper associated with the object
instance. |
| orm_insert_sentinel([name, type_], *, [default, omit_from_statements]) | Provides a surrogatemapped_column()that generates
a so-calledsentinelcolumn, allowing efficient bulk
inserts with deterministic RETURNING sorting for tables that don’t
otherwise have qualifying primary key configurations. |
| polymorphic_union(table_map, typecolname[, aliasname, cast_nulls]) | Create aUNIONstatement used by a polymorphic mapper. |
| reconstructor(fn) | Decorate a method as the ‘reconstructor’ hook. |
| registry | Generalized registry for mapping classes. |
| synonym_for(name[, map_column]) | Decorator that produces ansynonym()attribute in conjunction with a Python descriptor. |

   function sqlalchemy.orm.add_mapped_attribute(*target:Type[_O]*, *key:str*, *attr:MapperProperty[Any]*) → None

Add a new mapped attribute to an ORM mapped class.

E.g.:

```
add_mapped_attribute(User, "addresses", relationship(Address))
```

This may be used for ORM mappings that aren’t using a declarative
metaclass that intercepts attribute set operations.

Added in version 2.0.

     function sqlalchemy.orm.as_declarative(***kw:Any*) → Callable[[Type[_T]], Type[_T]]

Class decorator which will adapt a given class into a
[declarative_base()](#sqlalchemy.orm.declarative_base).

This function makes use of the [registry.as_declarative_base()](#sqlalchemy.orm.registry.as_declarative_base)
method, by first creating a [registry](#sqlalchemy.orm.registry) automatically
and then invoking the decorator.

E.g.:

```
from sqlalchemy.orm import as_declarative

@as_declarative()
class Base:
    @declared_attr
    def __tablename__(cls):
        return cls.__name__.lower()

    id = Column(Integer, primary_key=True)

class MyMappedClass(Base): ...
```

See also

[registry.as_declarative_base()](#sqlalchemy.orm.registry.as_declarative_base)

     function sqlalchemy.orm.class_mapper(*class_:Type[_O]*, *configure:bool=True*) → [Mapper](#sqlalchemy.orm.Mapper)[_O]

Given a class, return the primary [Mapper](#sqlalchemy.orm.Mapper) associated
with the key.

Raises [UnmappedClassError](https://docs.sqlalchemy.org/en/20/orm/exceptions.html#sqlalchemy.orm.exc.UnmappedClassError) if no mapping is configured
on the given class, or [ArgumentError](https://docs.sqlalchemy.org/en/20/core/exceptions.html#sqlalchemy.exc.ArgumentError) if a non-class
object is passed.

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

```
inspect(some_mapped_class)
```

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

    function sqlalchemy.orm.clear_mappers() → None

Remove all mappers from all classes.

Changed in version 1.4: This function now locates all
[registry](#sqlalchemy.orm.registry) objects and calls upon the
[registry.dispose()](#sqlalchemy.orm.registry.dispose) method of each.

This function removes all instrumentation from classes and disposes
of their associated mappers.  Once called, the classes are unmapped
and can be later re-mapped with new mappers.

[clear_mappers()](#sqlalchemy.orm.clear_mappers) is *not* for normal use, as there is literally no
valid usage for it outside of very specific testing scenarios. Normally,
mappers are permanent structural components of user-defined classes, and
are never discarded independently of their class.  If a mapped class
itself is garbage collected, its mapper is automatically disposed of as
well. As such, [clear_mappers()](#sqlalchemy.orm.clear_mappers) is only for usage in test suites
that reuse the same classes with different mappings, which is itself an
extremely rare use case - the only such use case is in fact SQLAlchemy’s
own test suite, and possibly the test suites of other ORM extension
libraries which intend to test various combinations of mapper construction
upon a fixed set of classes.

    function sqlalchemy.orm.column_property(*column:_ORMColumnExprArgument[_T]*, **additional_columns:_ORMColumnExprArgument[Any]*, *group:str|None=None*, *deferred:bool=False*, *raiseload:bool=False*, *comparator_factory:Type[PropComparator[_T]]|None=None*, *init:_NoArg|bool=_NoArg.NO_ARG*, *repr:_NoArg|bool=_NoArg.NO_ARG*, *default:Any|None=_NoArg.NO_ARG*, *default_factory:_NoArg|Callable[[],_T]=_NoArg.NO_ARG*, *compare:_NoArg|bool=_NoArg.NO_ARG*, *kw_only:_NoArg|bool=_NoArg.NO_ARG*, *hash:_NoArg|bool|None=_NoArg.NO_ARG*, *active_history:bool=False*, *expire_on_flush:bool=True*, *info:_InfoType|None=None*, *doc:str|None=None*, *dataclass_metadata:_NoArg|Mapping[Any,Any]|None=_NoArg.NO_ARG*) → [MappedSQLExpression](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.MappedSQLExpression)[_T]

Provide a column-level property for use with a mapping.

With Declarative mappings, [column_property()](#sqlalchemy.orm.column_property) is used to
map read-only SQL expressions to a mapped class.

When using Imperative mappings, [column_property()](#sqlalchemy.orm.column_property) also
takes on the role of mapping table columns with additional features.
When using fully Declarative mappings, the [mapped_column()](#sqlalchemy.orm.mapped_column)
construct should be used for this purpose.

With Declarative Dataclass mappings, [column_property()](#sqlalchemy.orm.column_property)
is considered to be **read only**, and will not be included in the
Dataclass `__init__()` constructor.

The [column_property()](#sqlalchemy.orm.column_property) function returns an instance of
[ColumnProperty](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.ColumnProperty).

See also

[Using column_property](https://docs.sqlalchemy.org/en/20/orm/mapped_sql_expr.html#mapper-column-property-sql-expressions) - general use of
[column_property()](#sqlalchemy.orm.column_property) to map SQL expressions

[Applying Load, Persistence and Mapping Options for Imperative Table Columns](https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#orm-imperative-table-column-options) - usage of
[column_property()](#sqlalchemy.orm.column_property) with Imperative Table mappings to apply
additional options to a plain [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column) object

   Parameters:

- ***cols** – list of Column objects to be mapped.
- **active_history=False** – Used only for Imperative Table mappings, or legacy-style Declarative
  mappings (i.e. which have not been upgraded to
  [mapped_column()](#sqlalchemy.orm.mapped_column)), for column-based attributes that are
  expected to be writeable; use [mapped_column()](#sqlalchemy.orm.mapped_column) with
  [mapped_column.active_history](#sqlalchemy.orm.mapped_column.params.active_history) for Declarative mappings.
  See that parameter for functional details.
- **comparator_factory** – a class which extends
  [Comparator](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.ColumnProperty.Comparator) which provides custom SQL
  clause generation for comparison operations.
- **group** – a group name for this property when marked as deferred.
- **deferred** – when True, the column property is “deferred”, meaning that
  it does not load immediately, and is instead loaded when the
  attribute is first accessed on an instance.  See also
  [deferred()](https://docs.sqlalchemy.org/en/20/orm/queryguide/columns.html#sqlalchemy.orm.deferred).
- **doc** – optional string that will be applied as the doc on the
  class-bound descriptor.
- **expire_on_flush=True** – Disable expiry on flush.   A column_property() which refers
  to a SQL expression (and not a single table-bound column)
  is considered to be a “read only” property; populating it
  has no effect on the state of data, and it can only return
  database state.   For this reason a column_property()’s value
  is expired whenever the parent object is involved in a
  flush, that is, has any kind of “dirty” state within a flush.
  Setting this parameter to `False` will have the effect of
  leaving any existing value present after the flush proceeds.
  Note that the [Session](https://docs.sqlalchemy.org/en/20/orm/session_api.html#sqlalchemy.orm.Session) with default expiration
  settings still expires
  all attributes after a [Session.commit()](https://docs.sqlalchemy.org/en/20/orm/session_api.html#sqlalchemy.orm.Session.commit) call, however.
- **info** – Optional data dictionary which will be populated into the
  [MapperProperty.info](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.MapperProperty.info) attribute of this object.
- **raiseload** –
  if True, indicates the column should raise an error
  when undeferred, rather than loading the value.  This can be
  altered at query time by using the [deferred()](https://docs.sqlalchemy.org/en/20/orm/queryguide/columns.html#sqlalchemy.orm.deferred) option with
  raiseload=False.
  Added in version 1.4.
  See also
  [Using raiseload to prevent deferred column loads](https://docs.sqlalchemy.org/en/20/orm/queryguide/columns.html#orm-queryguide-deferred-raiseload)
- **init** – Specific to [Declarative Dataclass Mapping](https://docs.sqlalchemy.org/en/20/orm/dataclasses.html#orm-declarative-native-dataclasses),
  specifies if the mapped attribute should be part of the `__init__()`
  method as generated by the dataclass process.
- **repr** – Specific to [Declarative Dataclass Mapping](https://docs.sqlalchemy.org/en/20/orm/dataclasses.html#orm-declarative-native-dataclasses),
  specifies if the mapped attribute should be part of the `__repr__()`
  method as generated by the dataclass process.
- **default_factory** –
  Specific to
  [Declarative Dataclass Mapping](https://docs.sqlalchemy.org/en/20/orm/dataclasses.html#orm-declarative-native-dataclasses),
  specifies a default-value generation function that will take place
  as part of the `__init__()`
  method as generated by the dataclass process.
  See also
  [What are default, default_factory and insert_default and what should I use?](https://docs.sqlalchemy.org/en/20/faq/ormconfiguration.html#defaults-default-factory-insert-default)
  [mapped_column.default](#sqlalchemy.orm.mapped_column.params.default)
  [mapped_column.insert_default](#sqlalchemy.orm.mapped_column.params.insert_default)
- **compare** –
  Specific to
  [Declarative Dataclass Mapping](https://docs.sqlalchemy.org/en/20/orm/dataclasses.html#orm-declarative-native-dataclasses), indicates if this field
  should be included in comparison operations when generating the
  `__eq__()` and `__ne__()` methods for the mapped class.
  Added in version 2.0.0b4.
- **kw_only** – Specific to
  [Declarative Dataclass Mapping](https://docs.sqlalchemy.org/en/20/orm/dataclasses.html#orm-declarative-native-dataclasses), indicates if this field
  should be marked as keyword-only when generating the `__init__()`.
- **hash** –
  Specific to
  [Declarative Dataclass Mapping](https://docs.sqlalchemy.org/en/20/orm/dataclasses.html#orm-declarative-native-dataclasses), controls if this field
  is included when generating the `__hash__()` method for the mapped
  class.
  Added in version 2.0.36.
- **dataclass_metadata** –
  Specific to
  [Declarative Dataclass Mapping](https://docs.sqlalchemy.org/en/20/orm/dataclasses.html#orm-declarative-native-dataclasses), supplies metadata
  to be attached to the generated dataclass field.
  Added in version 2.0.42.

      function sqlalchemy.orm.configure_mappers() → None

Initialize the inter-mapper relationships of all mappers that
have been constructed thus far across all [registry](#sqlalchemy.orm.registry)
collections.

The configure step is used to reconcile and initialize the
[relationship()](https://docs.sqlalchemy.org/en/20/orm/relationship_api.html#sqlalchemy.orm.relationship) linkages between mapped classes, as well as to
invoke configuration events such as the
[MapperEvents.before_configured()](https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.MapperEvents.before_configured) and
[MapperEvents.after_configured()](https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.MapperEvents.after_configured), which may be used by ORM
extensions or user-defined extension hooks.

Mapper configuration is normally invoked automatically, the first time
mappings from a particular [registry](#sqlalchemy.orm.registry) are used, as well as
whenever mappings are used and additional not-yet-configured mappers have
been constructed. The automatic configuration process however is local only
to the [registry](#sqlalchemy.orm.registry) involving the target mapper and any related
[registry](#sqlalchemy.orm.registry) objects which it may depend on; this is
equivalent to invoking the [registry.configure()](#sqlalchemy.orm.registry.configure) method
on a particular [registry](#sqlalchemy.orm.registry).

By contrast, the [configure_mappers()](#sqlalchemy.orm.configure_mappers) function will invoke the
configuration process on all [registry](#sqlalchemy.orm.registry) objects that
exist in memory, and may be useful for scenarios where many individual
[registry](#sqlalchemy.orm.registry) objects that are nonetheless interrelated are
in use.

Changed in version 1.4: As of SQLAlchemy 1.4.0b2, this function works on a
per-[registry](#sqlalchemy.orm.registry) basis, locating all [registry](#sqlalchemy.orm.registry)
objects present and invoking the [registry.configure()](#sqlalchemy.orm.registry.configure) method
on each. The [registry.configure()](#sqlalchemy.orm.registry.configure) method may be preferred to
limit the configuration of mappers to those local to a particular
[registry](#sqlalchemy.orm.registry) and/or declarative base class.

Points at which automatic configuration is invoked include when a mapped
class is instantiated into an instance, as well as when ORM queries
are emitted using [Session.query()](https://docs.sqlalchemy.org/en/20/orm/session_api.html#sqlalchemy.orm.Session.query) or [Session.execute()](https://docs.sqlalchemy.org/en/20/orm/session_api.html#sqlalchemy.orm.Session.execute)
with an ORM-enabled statement.

The mapper configure process, whether invoked by
[configure_mappers()](#sqlalchemy.orm.configure_mappers) or from [registry.configure()](#sqlalchemy.orm.registry.configure),
provides several event hooks that can be used to augment the mapper
configuration step. These hooks include:

- [MapperEvents.before_configured()](https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.MapperEvents.before_configured) - called once before
  [configure_mappers()](#sqlalchemy.orm.configure_mappers) or [registry.configure()](#sqlalchemy.orm.registry.configure) does any
  work; this can be used to establish additional options, properties, or
  related mappings before the operation proceeds.
- [MapperEvents.mapper_configured()](https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.MapperEvents.mapper_configured) - called as each individual
  [Mapper](#sqlalchemy.orm.Mapper) is configured within the process; will include all
  mapper state except for backrefs set up by other mappers that are still
  to be configured.
- [MapperEvents.after_configured()](https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.MapperEvents.after_configured) - called once after
  [configure_mappers()](#sqlalchemy.orm.configure_mappers) or [registry.configure()](#sqlalchemy.orm.registry.configure) is
  complete; at this stage, all [Mapper](#sqlalchemy.orm.Mapper) objects that fall
  within the scope of the configuration operation will be fully configured.
  Note that the calling application may still have other mappings that
  haven’t been produced yet, such as if they are in modules as yet
  unimported, and may also have mappings that are still to be configured,
  if they are in other [registry](#sqlalchemy.orm.registry) collections not part of the
  current scope of configuration.

    function sqlalchemy.orm.declarative_base(***, *metadata:MetaData|None=None*, *mapper:Optional[Callable[...*, *Mapper[Any]]]=None*, *cls:Type[Any]=<class'object'>*, *name:str='Base'*, *class_registry:clsregistry._ClsRegistryType|None=None*, *type_annotation_map:_TypeAnnotationMapType|None=None*, *constructor:Callable[...*, *None]=<function_declarative_constructor>*, *metaclass:Type[Any]=<class'sqlalchemy.orm.decl_api.DeclarativeMeta'>*) → Any

Construct a base class for declarative class definitions.

The new base class will be given a metaclass that produces
appropriate [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) objects and makes
the appropriate [Mapper](#sqlalchemy.orm.Mapper) calls based on the
information provided declaratively in the class and any subclasses
of the class.

Changed in version 2.0: Note that the [declarative_base()](#sqlalchemy.orm.declarative_base)
function is superseded by the new [DeclarativeBase](#sqlalchemy.orm.DeclarativeBase) class,
which generates a new “base” class using subclassing, rather than
return value of a function.  This allows an approach that is compatible
with [PEP 484](https://peps.python.org/pep-0484/) typing tools.

The [declarative_base()](#sqlalchemy.orm.declarative_base) function is a shorthand version
of using the [registry.generate_base()](#sqlalchemy.orm.registry.generate_base)
method.  That is, the following:

```
from sqlalchemy.orm import declarative_base

Base = declarative_base()
```

Is equivalent to:

```
from sqlalchemy.orm import registry

mapper_registry = registry()
Base = mapper_registry.generate_base()
```

See the docstring for [registry](#sqlalchemy.orm.registry)
and [registry.generate_base()](#sqlalchemy.orm.registry.generate_base)
for more details.

Changed in version 1.4: The [declarative_base()](#sqlalchemy.orm.declarative_base)
function is now a specialization of the more generic
[registry](#sqlalchemy.orm.registry) class.  The function also moves to the
`sqlalchemy.orm` package from the `declarative.ext` package.

   Parameters:

- **metadata** – An optional [MetaData](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.MetaData) instance.  All
  [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) objects implicitly declared by
  subclasses of the base will share this MetaData.  A MetaData instance
  will be created if none is provided.  The
  [MetaData](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.MetaData) instance will be available via the
  `metadata` attribute of the generated declarative base class.
- **mapper** – An optional callable, defaults to [Mapper](#sqlalchemy.orm.Mapper). Will
  be used to map subclasses to their Tables.
- **cls** – Defaults to `object`. A type to use as the base for the generated
  declarative base class. May be a class or tuple of classes.
- **name** – Defaults to `Base`.  The display name for the generated
  class.  Customizing this is not required, but can improve clarity in
  tracebacks and debugging.
- **constructor** – Specify the implementation for the `__init__` function on a mapped
  class that has no `__init__` of its own.  Defaults to an
  implementation that assigns **kwargs for declared
  fields and relationships to an instance.  If `None` is supplied,
  no __init__ will be provided and construction will fall back to
  cls.__init__ by way of the normal Python semantics.
- **class_registry** – optional dictionary that will serve as the
  registry of class names-> mapped classes when string names
  are used to identify classes inside of [relationship()](https://docs.sqlalchemy.org/en/20/orm/relationship_api.html#sqlalchemy.orm.relationship)
  and others.  Allows two or more declarative base classes
  to share the same registry of class names for simplified
  inter-base relationships.
- **type_annotation_map** –
  optional dictionary of Python types to
  SQLAlchemy [TypeEngine](https://docs.sqlalchemy.org/en/20/core/type_api.html#sqlalchemy.types.TypeEngine) classes or instances.  This
  is used exclusively by the [MappedColumn](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.MappedColumn) construct
  to produce column types based on annotations within the
  [Mapped](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.Mapped) type.
  Added in version 2.0.
  See also
  [Customizing the Type Map](https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#orm-declarative-mapped-column-type-map)
- **metaclass** – Defaults to `DeclarativeMeta`.  A metaclass or __metaclass__
  compatible callable to use as the meta type of the generated
  declarative base class.

See also

[registry](#sqlalchemy.orm.registry)

     function sqlalchemy.orm.declarative_mixin(*cls:Type[_T]*) → Type[_T]

Mark a class as providing the feature of “declarative mixin”.

E.g.:

```
from sqlalchemy.orm import declared_attr
from sqlalchemy.orm import declarative_mixin

@declarative_mixin
class MyMixin:

    @declared_attr
    def __tablename__(cls):
        return cls.__name__.lower()

    __table_args__ = {"mysql_engine": "InnoDB"}
    __mapper_args__ = {"always_refresh": True}

    id = Column(Integer, primary_key=True)

class MyModel(MyMixin, Base):
    name = Column(String(1000))
```

The [declarative_mixin()](#sqlalchemy.orm.declarative_mixin) decorator currently does not modify
the given class in any way; it’s current purpose is strictly to assist
the [Mypy plugin](https://docs.sqlalchemy.org/en/20/orm/extensions/mypy.html) in being able to identify
SQLAlchemy declarative mixin classes when no other context is present.

Added in version 1.4.6.

Legacy Feature

This api is considered legacy and will be deprecated in the next
SQLAlchemy version.

See also

[Composing Mapped Hierarchies with Mixins](https://docs.sqlalchemy.org/en/20/orm/declarative_mixins.html)

[Using @declared_attr and Declarative Mixins](https://docs.sqlalchemy.org/en/20/orm/extensions/mypy.html#mypy-declarative-mixins) - in the
[Mypy plugin documentation](https://docs.sqlalchemy.org/en/20/orm/extensions/mypy.html)

     class sqlalchemy.orm.DeclarativeBase

*inherits from* `sqlalchemy.inspection.Inspectable`

Base class used for declarative class definitions.

The [DeclarativeBase](#sqlalchemy.orm.DeclarativeBase) allows for the creation of new
declarative bases in such a way that is compatible with type checkers:

```
from sqlalchemy.orm import DeclarativeBase

class Base(DeclarativeBase):
    pass
```

The above `Base` class is now usable as the base for new declarative
mappings.  The superclass makes use of the `__init_subclass__()`
method to set up new classes and metaclasses aren’t used.

When first used, the [DeclarativeBase](#sqlalchemy.orm.DeclarativeBase) class instantiates a new
[registry](#sqlalchemy.orm.registry) to be used with the base, assuming one was not
provided explicitly. The [DeclarativeBase](#sqlalchemy.orm.DeclarativeBase) class supports
class-level attributes which act as parameters for the construction of this
registry; such as to indicate a specific [MetaData](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.MetaData)
collection as well as a specific value for
[registry.type_annotation_map](#sqlalchemy.orm.registry.params.type_annotation_map):

```
from typing_extensions import Annotated

from sqlalchemy import BigInteger
from sqlalchemy import MetaData
from sqlalchemy import String
from sqlalchemy.orm import DeclarativeBase

bigint = Annotated[int, "bigint"]
my_metadata = MetaData()

class Base(DeclarativeBase):
    metadata = my_metadata
    type_annotation_map = {
        str: String().with_variant(String(255), "mysql", "mariadb"),
        bigint: BigInteger(),
    }
```

Class-level attributes which may be specified include:

  Parameters:

- **metadata** – optional [MetaData](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.MetaData) collection.
  If a [registry](#sqlalchemy.orm.registry) is constructed automatically, this
  [MetaData](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.MetaData) collection will be used to construct it.
  Otherwise, the local [MetaData](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.MetaData) collection will supersede
  that used by an existing [registry](#sqlalchemy.orm.registry) passed using the
  [DeclarativeBase.registry](#sqlalchemy.orm.DeclarativeBase.params.registry) parameter.
- **type_annotation_map** – optional type annotation map that will be
  passed to the [registry](#sqlalchemy.orm.registry) as
  [registry.type_annotation_map](#sqlalchemy.orm.registry.params.type_annotation_map).
- **registry** – supply a pre-existing [registry](#sqlalchemy.orm.registry) directly.

Added in version 2.0: Added [DeclarativeBase](#sqlalchemy.orm.DeclarativeBase), so that declarative
base classes may be constructed in such a way that is also recognized
by [PEP 484](https://peps.python.org/pep-0484/) type checkers.   As a result, [DeclarativeBase](#sqlalchemy.orm.DeclarativeBase)
and other subclassing-oriented APIs should be seen as
superseding previous “class returned by a function” APIs, namely
[declarative_base()](#sqlalchemy.orm.declarative_base) and [registry.generate_base()](#sqlalchemy.orm.registry.generate_base),
where the base class returned cannot be recognized by type checkers
without using plugins.

**__init__ behavior**

In a plain Python class, the base-most `__init__()` method in the class
hierarchy is `object.__init__()`, which accepts no arguments. However,
when the [DeclarativeBase](#sqlalchemy.orm.DeclarativeBase) subclass is first declared, the
class is given an `__init__()` method that links to the
[registry.constructor](#sqlalchemy.orm.registry.params.constructor) constructor function, if no
`__init__()` method is already present; this is the usual declarative
constructor that will assign keyword arguments as attributes on the
instance, assuming those attributes are established at the class level
(i.e. are mapped, or are linked to a descriptor). This constructor is
**never accessed by a mapped class without being called explicitly via
super()**, as mapped classes are themselves given an `__init__()` method
directly which calls [registry.constructor](#sqlalchemy.orm.registry.params.constructor), so in the
default case works independently of what the base-most `__init__()`
method does.

Changed in version 2.0.1: [DeclarativeBase](#sqlalchemy.orm.DeclarativeBase) has a default
constructor that links to [registry.constructor](#sqlalchemy.orm.registry.params.constructor) by
default, so that calls to `super().__init__()` can access this
constructor. Previously, due to an implementation mistake, this default
constructor was missing, and calling `super().__init__()` would invoke
`object.__init__()`.

The [DeclarativeBase](#sqlalchemy.orm.DeclarativeBase) subclass may also declare an explicit
`__init__()` method which will replace the use of the
[registry.constructor](#sqlalchemy.orm.registry.params.constructor) function at this level:

```
class Base(DeclarativeBase):
    def __init__(self, id=None):
        self.id = id
```

Mapped classes still will not invoke this constructor implicitly; it
remains only accessible by calling `super().__init__()`:

```
class MyClass(Base):
    def __init__(self, id=None, name=None):
        self.name = name
        super().__init__(id=id)
```

Note that this is a different behavior from what functions like the legacy
[declarative_base()](#sqlalchemy.orm.declarative_base) would do; the base created by those functions
would always install [registry.constructor](#sqlalchemy.orm.registry.params.constructor) for
`__init__()`.

| Member Name | Description |
| --- | --- |
| __mapper__ | TheMapperobject to which a particular class is
mapped. |
| __mapper_args__ | Dictionary of arguments which will be passed to theMapperconstructor. |
| __table__ | TheFromClauseto which a particular subclass is
mapped. |
| __table_args__ | A dictionary or tuple of arguments that will be passed to theTableconstructor.  SeeDeclarative Table Configurationfor background on the specific structure of this collection. |
| __tablename__ | String name to assign to the generatedTableobject, if not specified directly viaDeclarativeBase.__table__. |
| metadata | Refers to theMetaDatacollection that will be used
for newTableobjects. |
| registry | Refers to theregistryin use where newMapperobjects will be associated. |

   attribute [sqlalchemy.orm.DeclarativeBase.](#sqlalchemy.orm.DeclarativeBase)__mapper__: ClassVar[[Mapper](#sqlalchemy.orm.Mapper)[Any]]

The [Mapper](#sqlalchemy.orm.Mapper) object to which a particular class is
mapped.

May also be acquired using [inspect()](https://docs.sqlalchemy.org/en/20/core/inspection.html#sqlalchemy.inspect), e.g.
`inspect(klass)`.

    attribute [sqlalchemy.orm.DeclarativeBase.](#sqlalchemy.orm.DeclarativeBase)__mapper_args__: Any

Dictionary of arguments which will be passed to the
[Mapper](#sqlalchemy.orm.Mapper) constructor.

See also

[Mapper Configuration Options with Declarative](https://docs.sqlalchemy.org/en/20/orm/declarative_config.html#orm-declarative-mapper-options)

     attribute [sqlalchemy.orm.DeclarativeBase.](#sqlalchemy.orm.DeclarativeBase)__table__: ClassVar[[FromClause](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.FromClause)]

The [FromClause](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.FromClause) to which a particular subclass is
mapped.

This is usually an instance of [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) but may also
refer to other kinds of [FromClause](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.FromClause) such as
[Subquery](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.Subquery), depending on how the class is mapped.

See also

[Accessing Table and Metadata](https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#orm-declarative-metadata)

     attribute [sqlalchemy.orm.DeclarativeBase.](#sqlalchemy.orm.DeclarativeBase)__table_args__: Any

A dictionary or tuple of arguments that will be passed to the
[Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) constructor.  See
[Declarative Table Configuration](https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#orm-declarative-table-configuration)
for background on the specific structure of this collection.

See also

[Declarative Table Configuration](https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#orm-declarative-table-configuration)

     attribute [sqlalchemy.orm.DeclarativeBase.](#sqlalchemy.orm.DeclarativeBase)__tablename__: Any

String name to assign to the generated
[Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) object, if not specified directly via
[DeclarativeBase.__table__](#sqlalchemy.orm.DeclarativeBase.__table__).

See also

[Declarative Table with mapped_column()](https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#orm-declarative-table)

     attribute [sqlalchemy.orm.DeclarativeBase.](#sqlalchemy.orm.DeclarativeBase)metadata: ClassVar[[MetaData](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.MetaData)]

Refers to the [MetaData](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.MetaData) collection that will be used
for new [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) objects.

See also

[Accessing Table and Metadata](https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#orm-declarative-metadata)

     attribute [sqlalchemy.orm.DeclarativeBase.](#sqlalchemy.orm.DeclarativeBase)registry: ClassVar[[registry](#sqlalchemy.orm.registry)]

Refers to the [registry](#sqlalchemy.orm.registry) in use where new
[Mapper](#sqlalchemy.orm.Mapper) objects will be associated.

     class sqlalchemy.orm.DeclarativeBaseNoMeta

*inherits from* `sqlalchemy.inspection.Inspectable`

Same as [DeclarativeBase](#sqlalchemy.orm.DeclarativeBase), but does not use a metaclass
to intercept new attributes.

The [DeclarativeBaseNoMeta](#sqlalchemy.orm.DeclarativeBaseNoMeta) base may be used when use of
custom metaclasses is desirable.

Added in version 2.0.

| Member Name | Description |
| --- | --- |
| __mapper__ | TheMapperobject to which a particular class is
mapped. |
| __mapper_args__ | Dictionary of arguments which will be passed to theMapperconstructor. |
| __table__ | TheFromClauseto which a particular subclass is
mapped. |
| __table_args__ | A dictionary or tuple of arguments that will be passed to theTableconstructor.  SeeDeclarative Table Configurationfor background on the specific structure of this collection. |
| __tablename__ | String name to assign to the generatedTableobject, if not specified directly viaDeclarativeBase.__table__. |
| metadata | Refers to theMetaDatacollection that will be used
for newTableobjects. |
| registry | Refers to theregistryin use where newMapperobjects will be associated. |

   attribute [sqlalchemy.orm.DeclarativeBaseNoMeta.](#sqlalchemy.orm.DeclarativeBaseNoMeta)__mapper__: ClassVar[[Mapper](#sqlalchemy.orm.Mapper)[Any]]

The [Mapper](#sqlalchemy.orm.Mapper) object to which a particular class is
mapped.

May also be acquired using [inspect()](https://docs.sqlalchemy.org/en/20/core/inspection.html#sqlalchemy.inspect), e.g.
`inspect(klass)`.

    attribute [sqlalchemy.orm.DeclarativeBaseNoMeta.](#sqlalchemy.orm.DeclarativeBaseNoMeta)__mapper_args__: Any

Dictionary of arguments which will be passed to the
[Mapper](#sqlalchemy.orm.Mapper) constructor.

See also

[Mapper Configuration Options with Declarative](https://docs.sqlalchemy.org/en/20/orm/declarative_config.html#orm-declarative-mapper-options)

     attribute [sqlalchemy.orm.DeclarativeBaseNoMeta.](#sqlalchemy.orm.DeclarativeBaseNoMeta)__table__: [FromClause](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.FromClause) | None

The [FromClause](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.FromClause) to which a particular subclass is
mapped.

This is usually an instance of [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) but may also
refer to other kinds of [FromClause](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.FromClause) such as
[Subquery](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.Subquery), depending on how the class is mapped.

See also

[Accessing Table and Metadata](https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#orm-declarative-metadata)

     attribute [sqlalchemy.orm.DeclarativeBaseNoMeta.](#sqlalchemy.orm.DeclarativeBaseNoMeta)__table_args__: Any

A dictionary or tuple of arguments that will be passed to the
[Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) constructor.  See
[Declarative Table Configuration](https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#orm-declarative-table-configuration)
for background on the specific structure of this collection.

See also

[Declarative Table Configuration](https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#orm-declarative-table-configuration)

     attribute [sqlalchemy.orm.DeclarativeBaseNoMeta.](#sqlalchemy.orm.DeclarativeBaseNoMeta)__tablename__: Any

String name to assign to the generated
[Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) object, if not specified directly via
[DeclarativeBase.__table__](#sqlalchemy.orm.DeclarativeBase.__table__).

See also

[Declarative Table with mapped_column()](https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#orm-declarative-table)

     attribute [sqlalchemy.orm.DeclarativeBaseNoMeta.](#sqlalchemy.orm.DeclarativeBaseNoMeta)metadata: ClassVar[[MetaData](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.MetaData)]

Refers to the [MetaData](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.MetaData) collection that will be used
for new [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) objects.

See also

[Accessing Table and Metadata](https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#orm-declarative-metadata)

     attribute [sqlalchemy.orm.DeclarativeBaseNoMeta.](#sqlalchemy.orm.DeclarativeBaseNoMeta)registry: ClassVar[[registry](#sqlalchemy.orm.registry)]

Refers to the [registry](#sqlalchemy.orm.registry) in use where new
[Mapper](#sqlalchemy.orm.Mapper) objects will be associated.

     class sqlalchemy.orm.declared_attr

*inherits from* `sqlalchemy.orm.base._MappedAttribute`, `sqlalchemy.orm.decl_api._declared_attr_common`

Mark a class-level method as representing the definition of
a mapped property or Declarative directive.

[declared_attr](#sqlalchemy.orm.declared_attr) is typically applied as a decorator to a class
level method, turning the attribute into a scalar-like property that can be
invoked from the uninstantiated class. The Declarative mapping process
looks for these [declared_attr](#sqlalchemy.orm.declared_attr) callables as it scans classes,
and assumes any attribute marked with [declared_attr](#sqlalchemy.orm.declared_attr) will be a
callable that will produce an object specific to the Declarative mapping or
table configuration.

[declared_attr](#sqlalchemy.orm.declared_attr) is usually applicable to
[mixins](https://docs.sqlalchemy.org/en/20/orm/declarative_mixins.html), to define relationships that are to be
applied to different implementors of the class. It may also be used to
define dynamically generated column expressions and other Declarative
attributes.

Example:

```
class ProvidesUserMixin:
    "A mixin that adds a 'user' relationship to classes."

    user_id: Mapped[int] = mapped_column(ForeignKey("user_table.id"))

    @declared_attr
    def user(cls) -> Mapped["User"]:
        return relationship("User")
```

When used with Declarative directives such as `__tablename__`, the
[declared_attr.directive()](#sqlalchemy.orm.declared_attr.directive) modifier may be used which indicates
to [PEP 484](https://peps.python.org/pep-0484/) typing tools that the given method is not dealing with
[Mapped](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.Mapped) attributes:

```
class CreateTableName:
    @declared_attr.directive
    def __tablename__(cls) -> str:
        return cls.__name__.lower()
```

[declared_attr](#sqlalchemy.orm.declared_attr) can also be applied directly to mapped
classes, to allow for attributes that dynamically configure themselves
on subclasses when using mapped inheritance schemes.   Below
illustrates [declared_attr](#sqlalchemy.orm.declared_attr) to create a dynamic scheme
for generating the [Mapper.polymorphic_identity](#sqlalchemy.orm.Mapper.params.polymorphic_identity) parameter
for subclasses:

```
class Employee(Base):
    __tablename__ = "employee"

    id: Mapped[int] = mapped_column(primary_key=True)
    type: Mapped[str] = mapped_column(String(50))

    @declared_attr.directive
    def __mapper_args__(cls) -> Dict[str, Any]:
        if cls.__name__ == "Employee":
            return {
                "polymorphic_on": cls.type,
                "polymorphic_identity": "Employee",
            }
        else:
            return {"polymorphic_identity": cls.__name__}

class Engineer(Employee):
    pass
```

[declared_attr](#sqlalchemy.orm.declared_attr) supports decorating functions that are
explicitly decorated with `@classmethod`. This is never necessary from a
runtime perspective, however may be needed in order to support [PEP 484](https://peps.python.org/pep-0484/)
typing tools that don’t otherwise recognize the decorated function as
having class-level behaviors for the `cls` parameter:

```
class SomethingMixin:
    x: Mapped[int]
    y: Mapped[int]

    @declared_attr
    @classmethod
    def x_plus_y(cls) -> Mapped[int]:
        return column_property(cls.x + cls.y)
```

Added in version 2.0: - [declared_attr](#sqlalchemy.orm.declared_attr) can accommodate a
function decorated with `@classmethod` to help with [PEP 484](https://peps.python.org/pep-0484/)
integration where needed.

See also

[Composing Mapped Hierarchies with Mixins](https://docs.sqlalchemy.org/en/20/orm/declarative_mixins.html) - Declarative Mixin documentation with
background on use patterns for [declared_attr](#sqlalchemy.orm.declared_attr).

| Member Name | Description |
| --- | --- |
| cascading | Mark adeclared_attras cascading. |
| directive | Mark adeclared_attras decorating a Declarative
directive such as__tablename__or__mapper_args__. |

   attribute [sqlalchemy.orm.declared_attr.](#sqlalchemy.orm.declared_attr)cascading

Mark a [declared_attr](#sqlalchemy.orm.declared_attr) as cascading.

This is a special-use modifier which indicates that a column
or MapperProperty-based declared attribute should be configured
distinctly per mapped subclass, within a mapped-inheritance scenario.

Warning

The [declared_attr.cascading](#sqlalchemy.orm.declared_attr.cascading) modifier has several
limitations:

- The flag **only** applies to the use of [declared_attr](#sqlalchemy.orm.declared_attr)
  on declarative mixin classes and `__abstract__` classes; it
  currently has no effect when used on a mapped class directly.
- The flag **only** applies to normally-named attributes, e.g.
  not any special underscore attributes such as `__tablename__`.
  On these attributes it has **no** effect.
- The flag currently **does not allow further overrides** down
  the class hierarchy; if a subclass tries to override the
  attribute, a warning is emitted and the overridden attribute
  is skipped.  This is a limitation that it is hoped will be
  resolved at some point.

Below, both MyClass as well as MySubClass will have a distinct
`id` Column object established:

```
class HasIdMixin:
    @declared_attr.cascading
    def id(cls) -> Mapped[int]:
        if has_inherited_table(cls):
            return mapped_column(ForeignKey("myclass.id"), primary_key=True)
        else:
            return mapped_column(Integer, primary_key=True)

class MyClass(HasIdMixin, Base):
    __tablename__ = "myclass"
    # ...

class MySubClass(MyClass):
    """ """

    # ...
```

The behavior of the above configuration is that `MySubClass`
will refer to both its own `id` column as well as that of
`MyClass` underneath the attribute named `some_id`.

See also

[Declarative Inheritance](https://docs.sqlalchemy.org/en/20/orm/extensions/declarative/inheritance.html#declarative-inheritance)

[Using _orm.declared_attr() to generate table-specific inheriting columns](https://docs.sqlalchemy.org/en/20/orm/declarative_mixins.html#mixin-inheritance-columns)

     attribute [sqlalchemy.orm.declared_attr.](#sqlalchemy.orm.declared_attr)directive

Mark a [declared_attr](#sqlalchemy.orm.declared_attr) as decorating a Declarative
directive such as `__tablename__` or `__mapper_args__`.

The purpose of [declared_attr.directive](#sqlalchemy.orm.declared_attr.directive) is strictly to
support [PEP 484](https://peps.python.org/pep-0484/) typing tools, by allowing the decorated function
to have a return type that is **not** using the [Mapped](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.Mapped)
generic class, as would normally be the case when [declared_attr](#sqlalchemy.orm.declared_attr)
is used for columns and mapped properties.  At
runtime, the [declared_attr.directive](#sqlalchemy.orm.declared_attr.directive) returns the
[declared_attr](#sqlalchemy.orm.declared_attr) class unmodified.

E.g.:

```
class CreateTableName:
    @declared_attr.directive
    def __tablename__(cls) -> str:
        return cls.__name__.lower()
```

Added in version 2.0.

See also

[Composing Mapped Hierarchies with Mixins](https://docs.sqlalchemy.org/en/20/orm/declarative_mixins.html)

[declared_attr](#sqlalchemy.orm.declared_attr)

      function sqlalchemy.orm.has_inherited_table(*cls:Type[_O]*) → bool

Given a class, return True if any of the classes it inherits from has a
mapped table, otherwise return False.

This is used in declarative mixins to build attributes that behave
differently for the base class vs. a subclass in an inheritance
hierarchy.

See also

[Using Mixins and Base Classes with Mapped Inheritance Patterns](https://docs.sqlalchemy.org/en/20/orm/declarative_mixins.html#decl-mixin-inheritance)

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

Generate “identity key” tuples, as are used as keys in the
[Session.identity_map](https://docs.sqlalchemy.org/en/20/orm/session_api.html#sqlalchemy.orm.Session.identity_map) dictionary.

This function has several call styles:

- `identity_key(class, ident, identity_token=token)`
  This form receives a mapped class and a primary key scalar or
  tuple as an argument.
  E.g.:
  ```
  >>> identity_key(MyClass, (1, 2))
  (<class '__main__.MyClass'>, (1, 2), None)
  ```
     param class:
  mapped class (must be a positional argument)
    param ident:
  primary key, may be a scalar or tuple argument.
    param identity_token:
  optional identity token
  Added in version 1.2: added identity_token
- `identity_key(instance=instance)`
  This form will produce the identity key for a given instance.  The
  instance need not be persistent, only that its primary key attributes
  are populated (else the key will contain `None` for those missing
  values).
  E.g.:
  ```
  >>> instance = MyClass(1, 2)
  >>> identity_key(instance=instance)
  (<class '__main__.MyClass'>, (1, 2), None)
  ```
  In this form, the given instance is ultimately run though
  [Mapper.identity_key_from_instance()](#sqlalchemy.orm.Mapper.identity_key_from_instance), which will have the
  effect of performing a database check for the corresponding row
  if the object is expired.
    param instance:
  object instance (must be given as a keyword arg)
- `identity_key(class, row=row, identity_token=token)`
  This form is similar to the class/tuple form, except is passed a
  database result row as a [Row](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Row) or [RowMapping](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.RowMapping) object.
  E.g.:
  ```
  >>> row = engine.execute(text("select * from table where a=1 and b=2")).first()
  >>> identity_key(MyClass, row=row)
  (<class '__main__.MyClass'>, (1, 2), None)
  ```
     param class:
  mapped class (must be a positional argument)
    param row:
  [Row](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Row) row returned by a [CursorResult](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.CursorResult)
  (must be given as a keyword arg)
    param identity_token:
  optional identity token
  Added in version 1.2: added identity_token

    function sqlalchemy.orm.mapped_as_dataclass(*registry:RegistryType*, ***, *init:_NoArg|bool=_NoArg.NO_ARG*, *repr:_NoArg|bool=_NoArg.NO_ARG*, *eq:_NoArg|bool=_NoArg.NO_ARG*, *order:_NoArg|bool=_NoArg.NO_ARG*, *unsafe_hash:_NoArg|bool=_NoArg.NO_ARG*, *match_args:_NoArg|bool=_NoArg.NO_ARG*, *kw_only:_NoArg|bool=_NoArg.NO_ARG*, *dataclass_callable:_NoArg|Callable[...,Type[Any]]=_NoArg.NO_ARG*) → Callable[[Type[_O]], Type[_O]]

Standalone function form of [registry.mapped_as_dataclass()](#sqlalchemy.orm.registry.mapped_as_dataclass)
which may have better compatibility with mypy.

The [registry](#sqlalchemy.orm.registry) is passed as the first argument to the
decorator.

e.g.:

```
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_as_dataclass
from sqlalchemy.orm import mapped_column
from sqlalchemy.orm import registry

some_registry = registry()

@mapped_as_dataclass(some_registry)
class Relationships:
    __tablename__ = "relationships"

    entity_id1: Mapped[int] = mapped_column(primary_key=True)
    entity_id2: Mapped[int] = mapped_column(primary_key=True)
    level: Mapped[int] = mapped_column(Integer)
```

Added in version 2.0.44.

     function sqlalchemy.orm.mapped_column(*__name_pos:str|_TypeEngineArgument[Any]|SchemaEventTarget|None=None*, *__type_pos:_TypeEngineArgument[Any]|SchemaEventTarget|None=None*, **args:SchemaEventTarget*, *init:_NoArg|bool=_NoArg.NO_ARG*, *repr:_NoArg|bool=_NoArg.NO_ARG*, *default:Any|None=_NoArg.NO_ARG*, *default_factory:_NoArg|Callable[[],_T]=_NoArg.NO_ARG*, *compare:_NoArg|bool=_NoArg.NO_ARG*, *kw_only:_NoArg|bool=_NoArg.NO_ARG*, *hash:_NoArg|bool|None=_NoArg.NO_ARG*, *nullable:bool|Literal[SchemaConst.NULL_UNSPECIFIED]|None=SchemaConst.NULL_UNSPECIFIED*, *primary_key:bool|None=False*, *deferred:_NoArg|bool=_NoArg.NO_ARG*, *deferred_group:str|None=None*, *deferred_raiseload:bool|None=None*, *use_existing_column:bool=False*, *name:str|None=None*, *type_:_TypeEngineArgument[Any]|None=None*, *autoincrement:_AutoIncrementType='auto'*, *doc:str|None=None*, *key:str|None=None*, *index:bool|None=None*, *unique:bool|None=None*, *info:_InfoType|None=None*, *onupdate:Any|None=None*, *insert_default:Any|None=_NoArg.NO_ARG*, *server_default:_ServerDefaultArgument|None=None*, *server_onupdate:_ServerOnUpdateArgument|None=None*, *active_history:bool=False*, *quote:bool|None=None*, *system:bool=False*, *comment:str|None=None*, *sort_order:_NoArg|int=_NoArg.NO_ARG*, *dataclass_metadata:_NoArg|Mapping[Any,Any]|None=_NoArg.NO_ARG*, ***kw:Any*) → [MappedColumn](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.MappedColumn)[Any]

declare a new ORM-mapped [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column) construct
for use within [Declarative Table](https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#orm-declarative-table)
configuration.

The [mapped_column()](#sqlalchemy.orm.mapped_column) function provides an ORM-aware and
Python-typing-compatible construct which is used with
[declarative](https://docs.sqlalchemy.org/en/20/orm/mapping_styles.html#orm-declarative-mapping) mappings to indicate an
attribute that’s mapped to a Core [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column) object.  It
provides the equivalent feature as mapping an attribute to a
[Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column) object directly when using Declarative,
specifically when using [Declarative Table](https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#orm-declarative-table)
configuration.

Added in version 2.0.

[mapped_column()](#sqlalchemy.orm.mapped_column) is normally used with explicit typing along with
the [Mapped](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.Mapped) annotation type, where it can derive the SQL
type and nullability for the column based on what’s present within the
[Mapped](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.Mapped) annotation.   It also may be used without annotations
as a drop-in replacement for how [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column) is used in
Declarative mappings in SQLAlchemy 1.x style.

For usage examples of [mapped_column()](#sqlalchemy.orm.mapped_column), see the documentation
at [Declarative Table with mapped_column()](https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#orm-declarative-table).

See also

[Declarative Table with mapped_column()](https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#orm-declarative-table) - complete documentation

[ORM Declarative Models](https://docs.sqlalchemy.org/en/20/changelog/whatsnew_20.html#whatsnew-20-orm-declarative-typing) - migration notes for
Declarative mappings using 1.x style mappings

   Parameters:

- **__name** – String name to give to the [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column).  This
  is an optional, positional only argument that if present must be the
  first positional argument passed.  If omitted, the attribute name to
  which the [mapped_column()](#sqlalchemy.orm.mapped_column)  is mapped will be used as the SQL
  column name.
- **__type** – [TypeEngine](https://docs.sqlalchemy.org/en/20/core/type_api.html#sqlalchemy.types.TypeEngine) type or instance which will
  indicate the datatype to be associated with the [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column).
  This is an optional, positional-only argument that if present must
  immediately follow the `__name` parameter if present also, or otherwise
  be the first positional parameter.  If omitted, the ultimate type for
  the column may be derived either from the annotated type, or if a
  [ForeignKey](https://docs.sqlalchemy.org/en/20/core/constraints.html#sqlalchemy.schema.ForeignKey) is present, from the datatype of the
  referenced column.
- ***args** – Additional positional arguments include constructs such
  as [ForeignKey](https://docs.sqlalchemy.org/en/20/core/constraints.html#sqlalchemy.schema.ForeignKey), [CheckConstraint](https://docs.sqlalchemy.org/en/20/core/constraints.html#sqlalchemy.schema.CheckConstraint),
  and [Identity](https://docs.sqlalchemy.org/en/20/core/defaults.html#sqlalchemy.schema.Identity), which are passed through to the constructed
  [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column).
- **nullable** – Optional bool, whether the column should be “NULL” or
  “NOT NULL”. If omitted, the nullability is derived from the type
  annotation based on whether or not `typing.Optional` (or its equivalent)
  is present.  `nullable` defaults to `True` otherwise for non-primary
  key columns, and `False` for primary key columns.
- **primary_key** – optional bool, indicates the [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column)
  would be part of the table’s primary key or not.
- **deferred** –
  Optional bool - this keyword argument is consumed by the
  ORM declarative process, and is not part of the [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column)
  itself; instead, it indicates that this column should be “deferred” for
  loading as though mapped by [deferred()](https://docs.sqlalchemy.org/en/20/orm/queryguide/columns.html#sqlalchemy.orm.deferred).
  See also
  [Configuring Column Deferral on Mappings](https://docs.sqlalchemy.org/en/20/orm/queryguide/columns.html#orm-queryguide-deferred-declarative)
- **deferred_group** –
  Implies [mapped_column.deferred](#sqlalchemy.orm.mapped_column.params.deferred)
  to `True`, and set the [deferred.group](https://docs.sqlalchemy.org/en/20/orm/queryguide/columns.html#sqlalchemy.orm.deferred.params.group) parameter.
  See also
  [Loading deferred columns in groups](https://docs.sqlalchemy.org/en/20/orm/queryguide/columns.html#orm-queryguide-deferred-group)
- **deferred_raiseload** –
  Implies [mapped_column.deferred](#sqlalchemy.orm.mapped_column.params.deferred)
  to `True`, and set the [deferred.raiseload](https://docs.sqlalchemy.org/en/20/orm/queryguide/columns.html#sqlalchemy.orm.deferred.params.raiseload) parameter.
  See also
  [Using raiseload to prevent deferred column loads](https://docs.sqlalchemy.org/en/20/orm/queryguide/columns.html#orm-queryguide-deferred-raiseload)
- **use_existing_column** –
  if True, will attempt to locate the given
  column name on an inherited superclass (typically single inheriting
  superclass), and if present, will not produce a new column, mapping
  to the superclass column as though it were omitted from this class.
  This is used for mixins that add new columns to an inherited superclass.
  See also
  [Resolving Column Conflicts with use_existing_column](https://docs.sqlalchemy.org/en/20/orm/inheritance.html#orm-inheritance-column-conflicts)
  Added in version 2.0.0b4.
- **default** –
  Passed directly to the
  [Column.default](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column.params.default) parameter if the
  [mapped_column.insert_default](#sqlalchemy.orm.mapped_column.params.insert_default) parameter is not present.
  Additionally, when used with [Declarative Dataclass Mapping](https://docs.sqlalchemy.org/en/20/orm/dataclasses.html#orm-declarative-native-dataclasses),
  indicates a default Python value that should be applied to the keyword
  constructor within the generated `__init__()` method.
  Note that in the case of dataclass generation when
  [mapped_column.insert_default](#sqlalchemy.orm.mapped_column.params.insert_default) is not present, this means
  the [mapped_column.default](#sqlalchemy.orm.mapped_column.params.default) value is used in **two**
  places, both the `__init__()` method as well as the
  [Column.default](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column.params.default) parameter. While this behavior may
  change in a future release, for the moment this tends to “work out”; a
  default of `None` will mean that the [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column) gets no
  default generator, whereas a default that refers to a non-`None` Python
  or SQL expression value will be assigned up front on the object when
  `__init__()` is called, which is the same value that the Core
  [Insert](https://docs.sqlalchemy.org/en/20/core/dml.html#sqlalchemy.sql.expression.Insert) construct would use in any case, leading to the same
  end result.
  Note
  When using Core level column defaults that are callables to
  be interpreted by the underlying [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column) in conjunction
  with [ORM-mapped dataclasses](https://docs.sqlalchemy.org/en/20/orm/dataclasses.html#orm-declarative-native-dataclasses), especially those that are
  [context-aware default functions](https://docs.sqlalchemy.org/en/20/core/defaults.html#context-default-functions),
  **the** [mapped_column.insert_default](#sqlalchemy.orm.mapped_column.params.insert_default) **parameter must
  be used instead**.  This is necessary to disambiguate the callable from
  being interpreted as a dataclass level default.
  See also
  [What are default, default_factory and insert_default and what should I use?](https://docs.sqlalchemy.org/en/20/faq/ormconfiguration.html#defaults-default-factory-insert-default)
  [mapped_column.insert_default](#sqlalchemy.orm.mapped_column.params.insert_default)
  [mapped_column.default_factory](#sqlalchemy.orm.mapped_column.params.default_factory)
- **insert_default** –
  Passed directly to the
  [Column.default](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column.params.default) parameter; will supersede the value
  of [mapped_column.default](#sqlalchemy.orm.mapped_column.params.default) when present, however
  [mapped_column.default](#sqlalchemy.orm.mapped_column.params.default) will always apply to the
  constructor default for a dataclasses mapping.
  See also
  [What are default, default_factory and insert_default and what should I use?](https://docs.sqlalchemy.org/en/20/faq/ormconfiguration.html#defaults-default-factory-insert-default)
  [mapped_column.default](#sqlalchemy.orm.mapped_column.params.default)
  [mapped_column.default_factory](#sqlalchemy.orm.mapped_column.params.default_factory)
- **sort_order** –
  An integer that indicates how this mapped column
  should be sorted compared to the others when the ORM is creating a
  [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table). Among mapped columns that have the same
  value the default ordering is used, placing first the mapped columns
  defined in the main class, then the ones in the super classes.
  Defaults to 0. The sort is ascending.
  Added in version 2.0.4.
- **active_history=False** –
  When `True`, indicates that the “previous” value for a
  scalar attribute should be loaded when replaced, if not
  already loaded. Normally, history tracking logic for
  simple non-primary-key scalar values only needs to be
  aware of the “new” value in order to perform a flush. This
  flag is available for applications that make use of
  [get_history()](https://docs.sqlalchemy.org/en/20/orm/session_api.html#sqlalchemy.orm.attributes.get_history) or [Session.is_modified()](https://docs.sqlalchemy.org/en/20/orm/session_api.html#sqlalchemy.orm.Session.is_modified)
  which also need to know the “previous” value of the attribute.
  Added in version 2.0.10.
- **init** – Specific to [Declarative Dataclass Mapping](https://docs.sqlalchemy.org/en/20/orm/dataclasses.html#orm-declarative-native-dataclasses),
  specifies if the mapped attribute should be part of the `__init__()`
  method as generated by the dataclass process.
- **repr** – Specific to [Declarative Dataclass Mapping](https://docs.sqlalchemy.org/en/20/orm/dataclasses.html#orm-declarative-native-dataclasses),
  specifies if the mapped attribute should be part of the `__repr__()`
  method as generated by the dataclass process.
- **default_factory** –
  Specific to
  [Declarative Dataclass Mapping](https://docs.sqlalchemy.org/en/20/orm/dataclasses.html#orm-declarative-native-dataclasses),
  specifies a default-value generation function that will take place
  as part of the `__init__()`
  method as generated by the dataclass process.
  See also
  [What are default, default_factory and insert_default and what should I use?](https://docs.sqlalchemy.org/en/20/faq/ormconfiguration.html#defaults-default-factory-insert-default)
  [mapped_column.default](#sqlalchemy.orm.mapped_column.params.default)
  [mapped_column.insert_default](#sqlalchemy.orm.mapped_column.params.insert_default)
- **compare** –
  Specific to
  [Declarative Dataclass Mapping](https://docs.sqlalchemy.org/en/20/orm/dataclasses.html#orm-declarative-native-dataclasses), indicates if this field
  should be included in comparison operations when generating the
  `__eq__()` and `__ne__()` methods for the mapped class.
  Added in version 2.0.0b4.
- **kw_only** – Specific to
  [Declarative Dataclass Mapping](https://docs.sqlalchemy.org/en/20/orm/dataclasses.html#orm-declarative-native-dataclasses), indicates if this field
  should be marked as keyword-only when generating the `__init__()`.
- **hash** –
  Specific to
  [Declarative Dataclass Mapping](https://docs.sqlalchemy.org/en/20/orm/dataclasses.html#orm-declarative-native-dataclasses), controls if this field
  is included when generating the `__hash__()` method for the mapped
  class.
  Added in version 2.0.36.
- **dataclass_metadata** –
  Specific to
  [Declarative Dataclass Mapping](https://docs.sqlalchemy.org/en/20/orm/dataclasses.html#orm-declarative-native-dataclasses), supplies metadata
  to be attached to the generated dataclass field.
  Added in version 2.0.42.
- ****kw** – All remaining keyword arguments are passed through to the
  constructor for the [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column).

      class sqlalchemy.orm.MappedAsDataclass

Mixin class to indicate when mapping this class, also convert it to be
a dataclass.

See also

[Declarative Dataclass Mapping](https://docs.sqlalchemy.org/en/20/orm/dataclasses.html#orm-declarative-native-dataclasses) - complete background
on SQLAlchemy native dataclass mapping

Added in version 2.0.

     class sqlalchemy.orm.MappedClassProtocol

*inherits from* `typing.Protocol`

A protocol representing a SQLAlchemy mapped class.

The protocol is generic on the type of class, use
`MappedClassProtocol[Any]` to allow any mapped class.

    class sqlalchemy.orm.Mapper

*inherits from* `sqlalchemy.orm.ORMFromClauseRole`, `sqlalchemy.orm.ORMEntityColumnsClauseRole`, `sqlalchemy.sql.cache_key.MemoizedHasCacheKey`, [sqlalchemy.orm.base.InspectionAttr](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.InspectionAttr), [sqlalchemy.log.Identified](https://docs.sqlalchemy.org/en/20/core/internals.html#sqlalchemy.log.Identified), `sqlalchemy.inspection.Inspectable`, `sqlalchemy.event.registry.EventTarget`, `typing.Generic`

Defines an association between a Python class and a database table or
other relational structure, so that ORM operations against the class may
proceed.

The [Mapper](#sqlalchemy.orm.Mapper) object is instantiated using mapping methods
present on the [registry](#sqlalchemy.orm.registry) object.  For information
about instantiating new [Mapper](#sqlalchemy.orm.Mapper) objects, see
[ORM Mapped Class Overview](https://docs.sqlalchemy.org/en/20/orm/mapping_styles.html).

| Member Name | Description |
| --- | --- |
| __init__() | Direct constructor for a newMapperobject. |
| add_properties() | Add the given dictionary of properties to this mapper,
usingadd_property. |
| add_property() | Add an individual MapperProperty to this mapper. |
| all_orm_descriptors | A namespace of allInspectionAttrattributes associated
with the mapped class. |
| attrs | A namespace of allMapperPropertyobjects
associated this mapper. |
| base_mapper | The base-mostMapperin an inheritance chain. |
| c | A synonym forMapper.columns. |
| cascade_iterator() | Iterate each element and its mapper in an object graph,
for all relationships that meet the given cascade rule. |
| class_ | The class to which thisMapperis mapped. |
| class_manager | TheClassManagerwhich maintains event listeners
and class-bound descriptors for thisMapper. |
| column_attrs | Return a namespace of allColumnPropertyproperties maintained by thisMapper. |
| columns | A collection ofColumnor other scalar expression
objects maintained by thisMapper. |
| common_parent() | Return true if the given mapper shares a
common inherited parent as this mapper. |
| composites | Return a namespace of allCompositeproperties maintained by thisMapper. |
| concrete | RepresentTrueif thisMapperis a concrete
inheritance mapper. |
| configured | RepresentTrueif thisMapperhas been configured. |
| get_property() | return a MapperProperty associated with the given key. |
| get_property_by_column() | Given aColumnobject, return theMapperPropertywhich maps this column. |
| identity_key_from_instance() | Return the identity key for the given instance, based on
its primary key attributes. |
| identity_key_from_primary_key() | Return an identity-map key for use in storing/retrieving an
item from an identity map. |
| identity_key_from_row() | Return an identity-map key for use in storing/retrieving an
item from the identity map. |
| inherits | References theMapperwhich thisMapperinherits from, if any. |
| is_mapper | Part of the inspection API. |
| is_sibling() | return true if the other mapper is an inheriting sibling to this
one.  common parent but different branch |
| isa() | Return True if the this mapper inherits from the given mapper. |
| local_table | The immediateFromClauseto which thisMapperrefers. |
| mapped_table |  |
| non_primary | RepresentTrueif thisMapperis a “non-primary”
mapper, e.g. a mapper that is used only to select rows but not for
persistence management. |
| persist_selectable | TheFromClauseto which thisMapperis mapped. |
| polymorphic_identity | Represent an identifier which is matched against theMapper.polymorphic_oncolumn during result row loading. |
| polymorphic_iterator() | Iterate through the collection including this mapper and
all descendant mappers. |
| polymorphic_map | A mapping of “polymorphic identity” identifiers mapped toMapperinstances, within an inheritance scenario. |
| polymorphic_on | TheColumnor SQL expression specified as thepolymorphic_onargument
for thisMapper, within an inheritance scenario. |
| primary_key | An iterable containing the collection ofColumnobjects
which comprise the ‘primary key’ of the mapped table, from the
perspective of thisMapper. |
| primary_key_from_instance() | Return the list of primary key values for the given
instance. |
| primary_mapper() | Return the primary mapper corresponding to this mapper’s class key
(class). |
| relationships | A namespace of allRelationshipproperties
maintained by thisMapper. |
| self_and_descendants | The collection including this mapper and all descendant mappers. |
| single | RepresentTrueif thisMapperis a single table
inheritance mapper. |
| synonyms | Return a namespace of allSynonymproperties maintained by thisMapper. |
| tables | A sequence containing the collection ofTableorTableClauseobjects which thisMapperis aware of. |
| validators | An immutable dictionary of attributes which have been decorated
using thevalidates()decorator. |
| with_polymorphic_mappers | The list ofMapperobjects included in the
default “polymorphic” query. |

   method [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)__init__(*class_:Type[_O]*, *local_table:FromClause|None=None*, *properties:Mapping[str,MapperProperty[Any]]|None=None*, *primary_key:Iterable[_ORMColumnExprArgument[Any]]|None=None*, *non_primary:bool=False*, *inherits:Mapper[Any]|Type[Any]|None=None*, *inherit_condition:_ColumnExpressionArgument[bool]|None=None*, *inherit_foreign_keys:Sequence[_ORMColumnExprArgument[Any]]|None=None*, *always_refresh:bool=False*, *version_id_col:_ORMColumnExprArgument[Any]|None=None*, *version_id_generator:Literal[False]|Callable[[Any],Any]|None=None*, *polymorphic_on:_ORMColumnExprArgument[Any]|str|MapperProperty[Any]|None=None*, *_polymorphic_map:Dict[Any,Mapper[Any]]|None=None*, *polymorphic_identity:Any|None=None*, *concrete:bool=False*, *with_polymorphic:_WithPolymorphicArg|None=None*, *polymorphic_abstract:bool=False*, *polymorphic_load:Literal['selectin','inline']|None=None*, *allow_partial_pks:bool=True*, *batch:bool=True*, *column_prefix:str|None=None*, *include_properties:Sequence[str]|None=None*, *exclude_properties:Sequence[str]|None=None*, *passive_updates:bool=True*, *passive_deletes:bool=False*, *confirm_deleted_rows:bool=True*, *eager_defaults:Literal[True,False,'auto']='auto'*, *legacy_is_orphan:bool=False*, *_compiled_cache_size:int=100*)

Direct constructor for a new [Mapper](#sqlalchemy.orm.Mapper) object.

The [Mapper](#sqlalchemy.orm.Mapper) constructor is not called directly, and
is normally invoked through the
use of the [registry](#sqlalchemy.orm.registry) object through either the
[Declarative](https://docs.sqlalchemy.org/en/20/orm/mapping_styles.html#orm-declarative-mapping) or
[Imperative](https://docs.sqlalchemy.org/en/20/orm/mapping_styles.html#orm-imperative-mapping) mapping styles.

Changed in version 2.0: The public facing `mapper()` function is
removed; for a classical mapping configuration, use the
[registry.map_imperatively()](#sqlalchemy.orm.registry.map_imperatively) method.

Parameters documented below may be passed to either the
[registry.map_imperatively()](#sqlalchemy.orm.registry.map_imperatively) method, or may be passed in the
`__mapper_args__` declarative class attribute described at
[Mapper Configuration Options with Declarative](https://docs.sqlalchemy.org/en/20/orm/declarative_config.html#orm-declarative-mapper-options).

  Parameters:

- **class_** – The class to be mapped.  When using Declarative,
  this argument is automatically passed as the declared class
  itself.
- **local_table** – The [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) or other
  [FromClause](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.FromClause) (i.e. selectable) to which the class is
  mapped. May be `None` if this mapper inherits from another mapper
  using single-table inheritance. When using Declarative, this
  argument is automatically passed by the extension, based on what is
  configured via the [DeclarativeBase.__table__](#sqlalchemy.orm.DeclarativeBase.__table__) attribute
  or via the [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) produced as a result of
  the [DeclarativeBase.__tablename__](#sqlalchemy.orm.DeclarativeBase.__tablename__) attribute being
  present.
- **polymorphic_abstract** –
  Indicates this class will be mapped in a
  polymorphic hierarchy, but not directly instantiated. The class is
  mapped normally, except that it has no requirement for a
  [Mapper.polymorphic_identity](#sqlalchemy.orm.Mapper.params.polymorphic_identity) within an inheritance
  hierarchy. The class however must be part of a polymorphic
  inheritance scheme which uses
  [Mapper.polymorphic_on](#sqlalchemy.orm.Mapper.params.polymorphic_on) at the base.
  Added in version 2.0.
  See also
  [Building Deeper Hierarchies with polymorphic_abstract](https://docs.sqlalchemy.org/en/20/orm/inheritance.html#orm-inheritance-abstract-poly)
- **always_refresh** – If True, all query operations for this mapped
  class will overwrite all data within object instances that already
  exist within the session, erasing any in-memory changes with
  whatever information was loaded from the database. Usage of this
  flag is highly discouraged; as an alternative, see the method
  [Query.populate_existing()](https://docs.sqlalchemy.org/en/20/orm/queryguide/query.html#sqlalchemy.orm.Query.populate_existing).
- **allow_partial_pks** –
  Defaults to True.  Indicates that a
  composite primary key with some NULL values should be considered as
  possibly existing within the database. This affects whether a
  mapper will assign an incoming row to an existing identity, as well
  as if [Session.merge()](https://docs.sqlalchemy.org/en/20/orm/session_api.html#sqlalchemy.orm.Session.merge) will check the database first for a
  particular primary key value. A “partial primary key” can occur if
  one has mapped to an OUTER JOIN, for example.
  The [Mapper.allow_partial_pks](#sqlalchemy.orm.Mapper.params.allow_partial_pks) parameter also
  indicates to the ORM relationship lazy loader, when loading a
  many-to-one related object, if a composite primary key that has
  partial NULL values should result in an attempt to load from the
  database, or if a load attempt is not necessary.
  Added in version 2.0.36: [Mapper.allow_partial_pks](#sqlalchemy.orm.Mapper.params.allow_partial_pks)
  is consulted by the relationship lazy loader strategy, such that
  when set to False, a SELECT for a composite primary key that
  has partial NULL values will not be emitted.
- **batch** – Defaults to `True`, indicating that save operations
  of multiple entities can be batched together for efficiency.
  Setting to False indicates
  that an instance will be fully saved before saving the next
  instance.  This is used in the extremely rare case that a
  [MapperEvents](https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.MapperEvents) listener requires being called
  in between individual row persistence operations.
- **column_prefix** –
  A string which will be prepended
  to the mapped attribute name when [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column)
  objects are automatically assigned as attributes to the
  mapped class.  Does not affect [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column) objects that
  are mapped explicitly in the [Mapper.properties](#sqlalchemy.orm.Mapper.params.properties)
  dictionary.
  This parameter is typically useful with imperative mappings
  that keep the [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) object separate.  Below, assuming
  the `user_table` [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) object has columns named
  `user_id`, `user_name`, and `password`:
  ```
  class User(Base):
      __table__ = user_table
      __mapper_args__ = {"column_prefix": "_"}
  ```
  The above mapping will assign the `user_id`, `user_name`, and
  `password` columns to attributes named `_user_id`,
  `_user_name`, and `_password` on the mapped `User` class.
  The [Mapper.column_prefix](#sqlalchemy.orm.Mapper.params.column_prefix) parameter is uncommon in
  modern use. For dealing with reflected tables, a more flexible
  approach to automating a naming scheme is to intercept the
  [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column) objects as they are reflected; see the section
  [Automating Column Naming Schemes from Reflected Tables](https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#mapper-automated-reflection-schemes) for notes on this usage
  pattern.
- **concrete** –
  If True, indicates this mapper should use concrete
  table inheritance with its parent mapper.
  See the section [Concrete Table Inheritance](https://docs.sqlalchemy.org/en/20/orm/inheritance.html#concrete-inheritance) for an example.
- **confirm_deleted_rows** – defaults to True; when a DELETE occurs
  of one more rows based on specific primary keys, a warning is
  emitted when the number of rows matched does not equal the number
  of rows expected.  This parameter may be set to False to handle the
  case where database ON DELETE CASCADE rules may be deleting some of
  those rows automatically.  The warning may be changed to an
  exception in a future release.
- **eager_defaults** –
  if True, the ORM will immediately fetch the
  value of server-generated default values after an INSERT or UPDATE,
  rather than leaving them as expired to be fetched on next access.
  This can be used for event schemes where the server-generated values
  are needed immediately before the flush completes.
  The fetch of values occurs either by using `RETURNING` inline
  with the `INSERT` or `UPDATE` statement, or by adding an
  additional `SELECT` statement subsequent to the `INSERT` or
  `UPDATE`, if the backend does not support `RETURNING`.
  The use of `RETURNING` is extremely performant in particular for
  `INSERT` statements where SQLAlchemy can take advantage of
  [insertmanyvalues](https://docs.sqlalchemy.org/en/20/core/connections.html#engine-insertmanyvalues), whereas the use of
  an additional `SELECT` is relatively poor performing, adding
  additional SQL round trips which would be unnecessary if these new
  attributes are not to be accessed in any case.
  For this reason, [Mapper.eager_defaults](#sqlalchemy.orm.Mapper.params.eager_defaults) defaults to the
  string value `"auto"`, which indicates that server defaults for
  INSERT should be fetched using `RETURNING` if the backing database
  supports it and if the dialect in use supports “insertmanyreturning”
  for an INSERT statement. If the backing database does not support
  `RETURNING` or “insertmanyreturning” is not available, server
  defaults will not be fetched.
  Changed in version 2.0.0rc1: added the “auto” option for
  [Mapper.eager_defaults](#sqlalchemy.orm.Mapper.params.eager_defaults)
  See also
  [Fetching Server-Generated Defaults](https://docs.sqlalchemy.org/en/20/orm/persistence_techniques.html#orm-server-defaults)
  Changed in version 2.0.0: RETURNING now works with multiple rows
  INSERTed at once using the
  [insertmanyvalues](https://docs.sqlalchemy.org/en/20/core/connections.html#engine-insertmanyvalues) feature, which
  among other things allows the [Mapper.eager_defaults](#sqlalchemy.orm.Mapper.params.eager_defaults)
  feature to be very performant on supporting backends.
- **exclude_properties** –
  A list or set of string column names to
  be excluded from mapping.
  See also
  [Mapping a Subset of Table Columns](https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#include-exclude-cols)
- **include_properties** –
  An inclusive list or set of string column
  names to map.
  See also
  [Mapping a Subset of Table Columns](https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#include-exclude-cols)
- **inherits** –
  A mapped class or the corresponding
  [Mapper](#sqlalchemy.orm.Mapper)
  of one indicating a superclass to which this [Mapper](#sqlalchemy.orm.Mapper)
  should *inherit* from.   The mapped class here must be a subclass
  of the other mapper’s class.   When using Declarative, this argument
  is passed automatically as a result of the natural class
  hierarchy of the declared classes.
  See also
  [Mapping Class Inheritance Hierarchies](https://docs.sqlalchemy.org/en/20/orm/inheritance.html)
- **inherit_condition** – For joined table inheritance, a SQL
  expression which will
  define how the two tables are joined; defaults to a natural join
  between the two tables.
- **inherit_foreign_keys** – When `inherit_condition` is used and
  the columns present are missing a [ForeignKey](https://docs.sqlalchemy.org/en/20/core/constraints.html#sqlalchemy.schema.ForeignKey)
  configuration, this parameter can be used to specify which columns
  are “foreign”.  In most cases can be left as `None`.
- **legacy_is_orphan** –
  Boolean, defaults to `False`.
  When `True`, specifies that “legacy” orphan consideration
  is to be applied to objects mapped by this mapper, which means
  that a pending (that is, not persistent) object is auto-expunged
  from an owning [Session](https://docs.sqlalchemy.org/en/20/orm/session_api.html#sqlalchemy.orm.Session) only when it is de-associated
  from *all* parents that specify a `delete-orphan` cascade towards
  this mapper.  The new default behavior is that the object is
  auto-expunged when it is de-associated with *any* of its parents
  that specify `delete-orphan` cascade.  This behavior is more
  consistent with that of a persistent object, and allows behavior to
  be consistent in more scenarios independently of whether or not an
  orphan object has been flushed yet or not.
  See the change note and example at [The consideration of a “pending” object as an “orphan” has been made more aggressive](https://docs.sqlalchemy.org/en/20/changelog/migration_08.html#legacy-is-orphan-addition)
  for more detail on this change.
- **non_primary** –
  Specify that this [Mapper](#sqlalchemy.orm.Mapper)
  is in addition
  to the “primary” mapper, that is, the one used for persistence.
  The [Mapper](#sqlalchemy.orm.Mapper) created here may be used for ad-hoc
  mapping of the class to an alternate selectable, for loading
  only.
  See also
  [Relationship to Aliased Class](https://docs.sqlalchemy.org/en/20/orm/join_conditions.html#relationship-aliased-class) - the new pattern that removes
  the need for the [Mapper.non_primary](#sqlalchemy.orm.Mapper.params.non_primary) flag.
- **passive_deletes** –
  Indicates DELETE behavior of foreign key
  columns when a joined-table inheritance entity is being deleted.
  Defaults to `False` for a base mapper; for an inheriting mapper,
  defaults to `False` unless the value is set to `True`
  on the superclass mapper.
  When `True`, it is assumed that ON DELETE CASCADE is configured
  on the foreign key relationships that link this mapper’s table
  to its superclass table, so that when the unit of work attempts
  to delete the entity, it need only emit a DELETE statement for the
  superclass table, and not this table.
  When `False`, a DELETE statement is emitted for this mapper’s
  table individually.  If the primary key attributes local to this
  table are unloaded, then a SELECT must be emitted in order to
  validate these attributes; note that the primary key columns
  of a joined-table subclass are not part of the “primary key” of
  the object as a whole.
  Note that a value of `True` is **always** forced onto the
  subclass mappers; that is, it’s not possible for a superclass
  to specify passive_deletes without this taking effect for
  all subclass mappers.
  See also
  [Using foreign key ON DELETE cascade with ORM relationships](https://docs.sqlalchemy.org/en/20/orm/cascades.html#passive-deletes) - description of similar feature as
  used with [relationship()](https://docs.sqlalchemy.org/en/20/orm/relationship_api.html#sqlalchemy.orm.relationship)
  [mapper.passive_updates](#sqlalchemy.orm.Mapper.mapper.params.passive_updates) - supporting ON UPDATE
  CASCADE for joined-table inheritance mappers
- **passive_updates** –
  Indicates UPDATE behavior of foreign key
  columns when a primary key column changes on a joined-table
  inheritance mapping.   Defaults to `True`.
  When True, it is assumed that ON UPDATE CASCADE is configured on
  the foreign key in the database, and that the database will handle
  propagation of an UPDATE from a source column to dependent columns
  on joined-table rows.
  When False, it is assumed that the database does not enforce
  referential integrity and will not be issuing its own CASCADE
  operation for an update.  The unit of work process will
  emit an UPDATE statement for the dependent columns during a
  primary key change.
  See also
  [Mutable Primary Keys / Update Cascades](https://docs.sqlalchemy.org/en/20/orm/relationship_persistence.html#passive-updates) - description of a similar feature as
  used with [relationship()](https://docs.sqlalchemy.org/en/20/orm/relationship_api.html#sqlalchemy.orm.relationship)
  [mapper.passive_deletes](#sqlalchemy.orm.Mapper.mapper.params.passive_deletes) - supporting ON DELETE
  CASCADE for joined-table inheritance mappers
- **polymorphic_load** –
  Specifies “polymorphic loading” behavior
  for a subclass in an inheritance hierarchy (joined and single
  table inheritance only).   Valid values are:
  > - “‘inline’” - specifies this class should be part of
  >   the “with_polymorphic” mappers, e.g. its columns will be included
  >   in a SELECT query against the base.
  > - “‘selectin’” - specifies that when instances of this class
  >   are loaded, an additional SELECT will be emitted to retrieve
  >   the columns specific to this subclass.  The SELECT uses
  >   IN to fetch multiple subclasses at once.
  Added in version 1.2.
  See also
  [Configuring with_polymorphic() on mappers](https://docs.sqlalchemy.org/en/20/orm/queryguide/inheritance.html#with-polymorphic-mapper-config)
  [Using selectin_polymorphic()](https://docs.sqlalchemy.org/en/20/orm/queryguide/inheritance.html#polymorphic-selectin)
- **polymorphic_on** –
  Specifies the column, attribute, or
  SQL expression used to determine the target class for an
  incoming row, when inheriting classes are present.
  May be specified as a string attribute name, or as a SQL
  expression such as a [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column) or in a Declarative
  mapping a [mapped_column()](#sqlalchemy.orm.mapped_column) object.  It is typically
  expected that the SQL expression corresponds to a column in the
  base-most mapped [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table):
  ```
  class Employee(Base):
      __tablename__ = "employee"
      id: Mapped[int] = mapped_column(primary_key=True)
      discriminator: Mapped[str] = mapped_column(String(50))
      __mapper_args__ = {
          "polymorphic_on": discriminator,
          "polymorphic_identity": "employee",
      }
  ```
  It may also be specified
  as a SQL expression, as in this example where we
  use the [case()](https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.case) construct to provide a conditional
  approach:
  ```
  class Employee(Base):
      __tablename__ = "employee"
      id: Mapped[int] = mapped_column(primary_key=True)
      discriminator: Mapped[str] = mapped_column(String(50))
      __mapper_args__ = {
          "polymorphic_on": case(
              (discriminator == "EN", "engineer"),
              (discriminator == "MA", "manager"),
              else_="employee",
          ),
          "polymorphic_identity": "employee",
      }
  ```
  It may also refer to any attribute using its string name,
  which is of particular use when using annotated column
  configurations:
  ```
  class Employee(Base):
      __tablename__ = "employee"
      id: Mapped[int] = mapped_column(primary_key=True)
      discriminator: Mapped[str]
      __mapper_args__ = {
          "polymorphic_on": "discriminator",
          "polymorphic_identity": "employee",
      }
  ```
  When setting `polymorphic_on` to reference an
  attribute or expression that’s not present in the
  locally mapped [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table), yet the value
  of the discriminator should be persisted to the database,
  the value of the
  discriminator is not automatically set on new
  instances; this must be handled by the user,
  either through manual means or via event listeners.
  A typical approach to establishing such a listener
  looks like:
  ```
  from sqlalchemy import event
  from sqlalchemy.orm import object_mapper
  @event.listens_for(Employee, "init", propagate=True)
  def set_identity(instance, *arg, **kw):
      mapper = object_mapper(instance)
      instance.discriminator = mapper.polymorphic_identity
  ```
  Where above, we assign the value of `polymorphic_identity`
  for the mapped class to the `discriminator` attribute,
  thus persisting the value to the `discriminator` column
  in the database.
  Warning
  Currently, **only one discriminator column may be set**, typically
  on the base-most class in the hierarchy. “Cascading” polymorphic
  columns are not yet supported.
  See also
  [Mapping Class Inheritance Hierarchies](https://docs.sqlalchemy.org/en/20/orm/inheritance.html)
- **polymorphic_identity** –
  Specifies the value which
  identifies this particular class as returned by the column expression
  referred to by the [Mapper.polymorphic_on](#sqlalchemy.orm.Mapper.params.polymorphic_on) setting. As
  rows are received, the value corresponding to the
  [Mapper.polymorphic_on](#sqlalchemy.orm.Mapper.params.polymorphic_on) column expression is compared
  to this value, indicating which subclass should be used for the newly
  reconstructed object.
  See also
  [Mapping Class Inheritance Hierarchies](https://docs.sqlalchemy.org/en/20/orm/inheritance.html)
- **properties** –
  A dictionary mapping the string names of object
  attributes to [MapperProperty](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.MapperProperty) instances, which define the
  persistence behavior of that attribute.  Note that
  [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column)
  objects present in
  the mapped [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) are automatically placed into
  `ColumnProperty` instances upon mapping, unless overridden.
  When using Declarative, this argument is passed automatically,
  based on all those [MapperProperty](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.MapperProperty) instances declared
  in the declared class body.
  See also
  [The properties dictionary](https://docs.sqlalchemy.org/en/20/orm/mapping_styles.html#orm-mapping-properties) - in the
  [ORM Mapped Class Overview](https://docs.sqlalchemy.org/en/20/orm/mapping_styles.html)
- **primary_key** –
  A list of [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column)
  objects, or alternatively string names of attribute names which
  refer to [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column), which define
  the primary key to be used against this mapper’s selectable unit.
  This is normally simply the primary key of the `local_table`, but
  can be overridden here.
  Changed in version 2.0.2: [Mapper.primary_key](#sqlalchemy.orm.Mapper.params.primary_key)
  arguments may be indicated as string attribute names as well.
  See also
  [Mapping to an Explicit Set of Primary Key Columns](https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#mapper-primary-key) - background and example use
- **version_id_col** –
  A [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column)
  that will be used to keep a running version id of rows
  in the table.  This is used to detect concurrent updates or
  the presence of stale data in a flush.  The methodology is to
  detect if an UPDATE statement does not match the last known
  version id, a
  [StaleDataError](https://docs.sqlalchemy.org/en/20/orm/exceptions.html#sqlalchemy.orm.exc.StaleDataError) exception is
  thrown.
  By default, the column must be of [Integer](https://docs.sqlalchemy.org/en/20/core/type_basics.html#sqlalchemy.types.Integer) type,
  unless `version_id_generator` specifies an alternative version
  generator.
  See also
  [Configuring a Version Counter](https://docs.sqlalchemy.org/en/20/orm/versioning.html#mapper-version-counter) - discussion of version counting
  and rationale.
- **version_id_generator** –
  Define how new version ids should
  be generated.  Defaults to `None`, which indicates that
  a simple integer counting scheme be employed.  To provide a custom
  versioning scheme, provide a callable function of the form:
  ```
  def generate_version(version):
      return next_version
  ```
  Alternatively, server-side versioning functions such as triggers,
  or programmatic versioning schemes outside of the version id
  generator may be used, by specifying the value `False`.
  Please see [Server Side Version Counters](https://docs.sqlalchemy.org/en/20/orm/versioning.html#server-side-version-counter) for a discussion
  of important points when using this option.
  See also
  [Custom Version Counters / Types](https://docs.sqlalchemy.org/en/20/orm/versioning.html#custom-version-counter)
  [Server Side Version Counters](https://docs.sqlalchemy.org/en/20/orm/versioning.html#server-side-version-counter)
- **with_polymorphic** –
  A tuple in the form `(<classes>,
  <selectable>)` indicating the default style of “polymorphic”
  loading, that is, which tables are queried at once. <classes> is
  any single or list of mappers and/or classes indicating the
  inherited classes that should be loaded at once. The special value
  `'*'` may be used to indicate all descending classes should be
  loaded immediately. The second tuple argument <selectable>
  indicates a selectable that will be used to query for multiple
  classes.
  The [Mapper.polymorphic_load](#sqlalchemy.orm.Mapper.params.polymorphic_load) parameter may be
  preferable over the use of [Mapper.with_polymorphic](#sqlalchemy.orm.Mapper.params.with_polymorphic)
  in modern mappings to indicate a per-subclass technique of
  indicating polymorphic loading styles.
  See also
  [Configuring with_polymorphic() on mappers](https://docs.sqlalchemy.org/en/20/orm/queryguide/inheritance.html#with-polymorphic-mapper-config)

      method [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)add_properties(*dict_of_properties*)

Add the given dictionary of properties to this mapper,
using add_property.

    method [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)add_property(*key:str*, *prop:Column[Any]|MapperProperty[Any]*) → None

Add an individual MapperProperty to this mapper.

If the mapper has not been configured yet, just adds the
property to the initial properties dictionary sent to the
constructor.  If this Mapper has already been configured, then
the given MapperProperty is configured immediately.

    attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)all_orm_descriptors

A namespace of all [InspectionAttr](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.InspectionAttr) attributes associated
with the mapped class.

These attributes are in all cases Python [descriptors](https://docs.sqlalchemy.org/en/20/glossary.html#term-descriptors)
associated with the mapped class or its superclasses.

This namespace includes attributes that are mapped to the class
as well as attributes declared by extension modules.
It includes any Python descriptor type that inherits from
[InspectionAttr](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.InspectionAttr).  This includes
[QueryableAttribute](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.QueryableAttribute), as well as extension types such as
[hybrid_property](https://docs.sqlalchemy.org/en/20/orm/extensions/hybrid.html#sqlalchemy.ext.hybrid.hybrid_property), [hybrid_method](https://docs.sqlalchemy.org/en/20/orm/extensions/hybrid.html#sqlalchemy.ext.hybrid.hybrid_method) and
[AssociationProxy](https://docs.sqlalchemy.org/en/20/orm/extensions/associationproxy.html#sqlalchemy.ext.associationproxy.AssociationProxy).

To distinguish between mapped attributes and extension attributes,
the attribute [InspectionAttr.extension_type](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.InspectionAttr.extension_type) will refer
to a constant that distinguishes between different extension types.

The sorting of the attributes is based on the following rules:

1. Iterate through the class and its superclasses in order from
  subclass to superclass (i.e. iterate through `cls.__mro__`)
2. For each class, yield the attributes in the order in which they
  appear in `__dict__`, with the exception of those in step
  3 below.  In Python 3.6 and above this ordering will be the
  same as that of the class’ construction, with the exception
  of attributes that were added after the fact by the application
  or the mapper.
3. If a certain attribute key is also in the superclass `__dict__`,
  then it’s included in the iteration for that class, and not the
  class in which it first appeared.

The above process produces an ordering that is deterministic in terms
of the order in which attributes were assigned to the class.

Changed in version 1.3.19: ensured deterministic ordering for
[Mapper.all_orm_descriptors()](#sqlalchemy.orm.Mapper.all_orm_descriptors).

When dealing with a [QueryableAttribute](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.QueryableAttribute), the
`QueryableAttribute.property` attribute refers to the
[MapperProperty](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.MapperProperty) property, which is what you get when
referring to the collection of mapped properties via
[Mapper.attrs](#sqlalchemy.orm.Mapper.attrs).

Warning

The [Mapper.all_orm_descriptors](#sqlalchemy.orm.Mapper.all_orm_descriptors)
accessor namespace is an
instance of `OrderedProperties`.  This is
a dictionary-like object which includes a small number of
named methods such as `OrderedProperties.items()`
and `OrderedProperties.values()`.  When
accessing attributes dynamically, favor using the dict-access
scheme, e.g. `mapper.all_orm_descriptors[somename]` over
`getattr(mapper.all_orm_descriptors, somename)` to avoid name
collisions.

See also

[Mapper.attrs](#sqlalchemy.orm.Mapper.attrs)

     attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)attrs

A namespace of all [MapperProperty](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.MapperProperty) objects
associated this mapper.

This is an object that provides each property based on
its key name.  For instance, the mapper for a
`User` class which has `User.name` attribute would
provide `mapper.attrs.name`, which would be the
[ColumnProperty](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.ColumnProperty) representing the `name`
column.   The namespace object can also be iterated,
which would yield each [MapperProperty](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.MapperProperty).

[Mapper](#sqlalchemy.orm.Mapper) has several pre-filtered views
of this attribute which limit the types of properties
returned, including [synonyms](#sqlalchemy.orm.Mapper.synonyms), [column_attrs](#sqlalchemy.orm.Mapper.column_attrs),
[relationships](#sqlalchemy.orm.Mapper.relationships), and [composites](#sqlalchemy.orm.Mapper.composites).

Warning

The [Mapper.attrs](#sqlalchemy.orm.Mapper.attrs) accessor namespace is an
instance of `OrderedProperties`.  This is
a dictionary-like object which includes a small number of
named methods such as `OrderedProperties.items()`
and `OrderedProperties.values()`.  When
accessing attributes dynamically, favor using the dict-access
scheme, e.g. `mapper.attrs[somename]` over
`getattr(mapper.attrs, somename)` to avoid name collisions.

See also

[Mapper.all_orm_descriptors](#sqlalchemy.orm.Mapper.all_orm_descriptors)

     attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)base_mapper: [Mapper](#sqlalchemy.orm.Mapper)[Any]

The base-most [Mapper](#sqlalchemy.orm.Mapper) in an inheritance chain.

In a non-inheriting scenario, this attribute will always be this
[Mapper](#sqlalchemy.orm.Mapper).   In an inheritance scenario, it references
the [Mapper](#sqlalchemy.orm.Mapper) which is parent to all other [Mapper](#sqlalchemy.orm.Mapper)
objects in the inheritance chain.

This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.

    attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)c: ReadOnlyColumnCollection[str, [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column)[Any]]

A synonym for [Mapper.columns](#sqlalchemy.orm.Mapper.columns).

    method [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)cascade_iterator(*type_:str*, *state:InstanceState[_O]*, *halt_on:Callable[[InstanceState[Any]],bool]|None=None*) → Iterator[[Tuple](https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.Tuple)[[object](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.InstanceState.object), [Mapper](#sqlalchemy.orm.Mapper)[Any], [InstanceState](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.InstanceState)[Any], _InstanceDict]]

Iterate each element and its mapper in an object graph,
for all relationships that meet the given cascade rule.

  Parameters:

- **type_** –
  The name of the cascade rule (i.e. `"save-update"`, `"delete"`,
  etc.).
  Note
  the `"all"` cascade is not accepted here.  For a generic
  object traversal function, see [How do I walk all objects that are related to a given object?](https://docs.sqlalchemy.org/en/20/faq/sessions.html#faq-walk-objects).
- **state** – The lead InstanceState.  child items will be processed per
  the relationships defined for this object’s mapper.

  Returns:

the method yields individual object instances.

See also

[Cascades](https://docs.sqlalchemy.org/en/20/orm/cascades.html#unitofwork-cascades)

[How do I walk all objects that are related to a given object?](https://docs.sqlalchemy.org/en/20/faq/sessions.html#faq-walk-objects) - illustrates a generic function to
traverse all objects without relying on cascades.

     attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)class_: Type[_O]

The class to which this [Mapper](#sqlalchemy.orm.Mapper) is mapped.

    attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)class_manager: [ClassManager](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.ClassManager)[_O]

The [ClassManager](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.ClassManager) which maintains event listeners
and class-bound descriptors for this [Mapper](#sqlalchemy.orm.Mapper).

This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.

    attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)column_attrs

Return a namespace of all [ColumnProperty](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.ColumnProperty)
properties maintained by this [Mapper](#sqlalchemy.orm.Mapper).

See also

[Mapper.attrs](#sqlalchemy.orm.Mapper.attrs) - namespace of all
[MapperProperty](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.MapperProperty)
objects.

     attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)columns: ReadOnlyColumnCollection[str, [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column)[Any]]

A collection of [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column) or other scalar expression
objects maintained by this [Mapper](#sqlalchemy.orm.Mapper).

The collection behaves the same as that of the `c` attribute on
any [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) object,
except that only those columns included in
this mapping are present, and are keyed based on the attribute name
defined in the mapping, not necessarily the `key` attribute of the
[Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column) itself.   Additionally, scalar expressions mapped
by [column_property()](#sqlalchemy.orm.column_property) are also present here.

This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.

    method [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)common_parent(*other:Mapper[Any]*) → bool

Return true if the given mapper shares a
common inherited parent as this mapper.

    attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)composites

Return a namespace of all [Composite](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.Composite)
properties maintained by this [Mapper](#sqlalchemy.orm.Mapper).

See also

[Mapper.attrs](#sqlalchemy.orm.Mapper.attrs) - namespace of all
[MapperProperty](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.MapperProperty)
objects.

     attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)concrete: bool

Represent `True` if this [Mapper](#sqlalchemy.orm.Mapper) is a concrete
inheritance mapper.

This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.

    attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)configured: bool = False

Represent `True` if this [Mapper](#sqlalchemy.orm.Mapper) has been configured.

This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.

See also

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

     property entity

Part of the inspection API.

Returns self.class_.

    method [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)get_property(*key:str*, *_configure_mappers:bool=False*) → [MapperProperty](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.MapperProperty)[Any]

return a MapperProperty associated with the given key.

    method [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)get_property_by_column(*column:ColumnElement[_T]*) → [MapperProperty](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.MapperProperty)[_T]

Given a [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column) object, return the
[MapperProperty](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.MapperProperty) which maps this column.

    method [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)identity_key_from_instance(*instance:_O*) → _IdentityKeyType[_O]

Return the identity key for the given instance, based on
its primary key attributes.

If the instance’s state is expired, calling this method
will result in a database check to see if the object has been deleted.
If the row no longer exists,
[ObjectDeletedError](https://docs.sqlalchemy.org/en/20/orm/exceptions.html#sqlalchemy.orm.exc.ObjectDeletedError) is raised.

This value is typically also found on the instance state under the
attribute name key.

    method [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)identity_key_from_primary_key(*primary_key:Tuple[Any,...]*, *identity_token:Any|None=None*) → _IdentityKeyType[_O]

Return an identity-map key for use in storing/retrieving an
item from an identity map.

  Parameters:

**primary_key** – A list of values indicating the identifier.

      method [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)identity_key_from_row(*row:Row[Any]|RowMapping*, *identity_token:Any|None=None*, *adapter:ORMAdapter|None=None*) → _IdentityKeyType[_O]

Return an identity-map key for use in storing/retrieving an
item from the identity map.

  Parameters:

**row** –

A [Row](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Row) or [RowMapping](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.RowMapping) produced from a
result set that selected from the ORM mapped primary key columns.

Changed in version 2.0: [Row](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Row) or [RowMapping](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.RowMapping) are accepted
for the “row” argument

       attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)inherits: [Mapper](#sqlalchemy.orm.Mapper)[Any] | None

References the [Mapper](#sqlalchemy.orm.Mapper) which this [Mapper](#sqlalchemy.orm.Mapper)
inherits from, if any.

    attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)is_mapper = True

Part of the inspection API.

    method [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)is_sibling(*other:Mapper[Any]*) → bool

return true if the other mapper is an inheriting sibling to this
one.  common parent but different branch

    method [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)isa(*other:Mapper[Any]*) → bool

Return True if the this mapper inherits from the given mapper.

    property iterate_properties

return an iterator of all MapperProperty objects.

    attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)local_table: [FromClause](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.FromClause)

The immediate [FromClause](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.FromClause) to which this
[Mapper](#sqlalchemy.orm.Mapper) refers.

Typically is an instance of [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table), may be any
[FromClause](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.FromClause).

The “local” table is the
selectable that the [Mapper](#sqlalchemy.orm.Mapper) is directly responsible for
managing from an attribute access and flush perspective.   For
non-inheriting mappers, [Mapper.local_table](#sqlalchemy.orm.Mapper.local_table) will be the same
as [Mapper.persist_selectable](#sqlalchemy.orm.Mapper.persist_selectable).  For inheriting mappers,
[Mapper.local_table](#sqlalchemy.orm.Mapper.local_table) refers to the specific portion of
[Mapper.persist_selectable](#sqlalchemy.orm.Mapper.persist_selectable) that includes the columns to which
this [Mapper](#sqlalchemy.orm.Mapper) is loading/persisting, such as a particular
[Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) within a join.

See also

[Mapper.persist_selectable](#sqlalchemy.orm.Mapper.persist_selectable).

[Mapper.selectable](#sqlalchemy.orm.Mapper.selectable).

     attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)mapped_table

Deprecated since version 1.3: Use .persist_selectable

     property mapper: [Mapper](#sqlalchemy.orm.Mapper)[_O]

Part of the inspection API.

Returns self.

    attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)non_primary: bool

Represent `True` if this [Mapper](#sqlalchemy.orm.Mapper) is a “non-primary”
mapper, e.g. a mapper that is used only to select rows but not for
persistence management.

This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.

    attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)persist_selectable: [FromClause](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.FromClause)

The [FromClause](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.FromClause) to which this [Mapper](#sqlalchemy.orm.Mapper)
is mapped.

Typically is an instance of [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table), may be any
[FromClause](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.FromClause).

The [Mapper.persist_selectable](#sqlalchemy.orm.Mapper.persist_selectable) is similar to
[Mapper.local_table](#sqlalchemy.orm.Mapper.local_table), but represents the [FromClause](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.FromClause) that
represents the inheriting class hierarchy overall in an inheritance
scenario.

:attr.`.Mapper.persist_selectable` is also separate from the
[Mapper.selectable](#sqlalchemy.orm.Mapper.selectable) attribute, the latter of which may be an
alternate subquery used for selecting columns.
:attr.`.Mapper.persist_selectable` is oriented towards columns that
will be written on a persist operation.

See also

[Mapper.selectable](#sqlalchemy.orm.Mapper.selectable).

[Mapper.local_table](#sqlalchemy.orm.Mapper.local_table).

     attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)polymorphic_identity: Any | None

Represent an identifier which is matched against the
[Mapper.polymorphic_on](#sqlalchemy.orm.Mapper.polymorphic_on) column during result row loading.

Used only with inheritance, this object can be of any type which is
comparable to the type of column represented by
[Mapper.polymorphic_on](#sqlalchemy.orm.Mapper.polymorphic_on).

This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.

    method [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)polymorphic_iterator() → Iterator[[Mapper](#sqlalchemy.orm.Mapper)[Any]]

Iterate through the collection including this mapper and
all descendant mappers.

This includes not just the immediately inheriting mappers but
all their inheriting mappers as well.

To iterate through an entire hierarchy, use
`mapper.base_mapper.polymorphic_iterator()`.

    attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)polymorphic_map: Dict[Any, [Mapper](#sqlalchemy.orm.Mapper)[Any]]

A mapping of “polymorphic identity” identifiers mapped to
[Mapper](#sqlalchemy.orm.Mapper) instances, within an inheritance scenario.

The identifiers can be of any type which is comparable to the
type of column represented by [Mapper.polymorphic_on](#sqlalchemy.orm.Mapper.polymorphic_on).

An inheritance chain of mappers will all reference the same
polymorphic map object.  The object is used to correlate incoming
result rows to target mappers.

This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.

    attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)polymorphic_on: KeyedColumnElement[Any] | None

The [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column) or SQL expression specified as the
`polymorphic_on` argument
for this [Mapper](#sqlalchemy.orm.Mapper), within an inheritance scenario.

This attribute is normally a [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column) instance but
may also be an expression, such as one derived from
[cast()](https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.cast).

This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.

    attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)primary_key: [Tuple](https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.Tuple)[[ColumnElement](https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.ColumnElement)[Any], ...]

An iterable containing the collection of [Column](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Column)
objects
which comprise the ‘primary key’ of the mapped table, from the
perspective of this [Mapper](#sqlalchemy.orm.Mapper).

This list is against the selectable in
[Mapper.persist_selectable](#sqlalchemy.orm.Mapper.persist_selectable).
In the case of inheriting mappers, some columns may be managed by a
superclass mapper.  For example, in the case of a
[Join](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.Join), the
primary key is determined by all of the primary key columns across all
tables referenced by the [Join](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.Join).

The list is also not necessarily the same as the primary key column
collection associated with the underlying tables; the [Mapper](#sqlalchemy.orm.Mapper)
features a `primary_key` argument that can override what the
[Mapper](#sqlalchemy.orm.Mapper) considers as primary key columns.

This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.

    method [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)primary_key_from_instance(*instance:_O*) → Tuple[Any, ...]

Return the list of primary key values for the given
instance.

If the instance’s state is expired, calling this method
will result in a database check to see if the object has been deleted.
If the row no longer exists,
[ObjectDeletedError](https://docs.sqlalchemy.org/en/20/orm/exceptions.html#sqlalchemy.orm.exc.ObjectDeletedError) is raised.

    method [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)primary_mapper() → [Mapper](#sqlalchemy.orm.Mapper)[Any]

Return the primary mapper corresponding to this mapper’s class key
(class).

    attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)relationships

A namespace of all [Relationship](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.Relationship) properties
maintained by this [Mapper](#sqlalchemy.orm.Mapper).

Warning

the [Mapper.relationships](#sqlalchemy.orm.Mapper.relationships) accessor namespace is an
instance of `OrderedProperties`.  This is
a dictionary-like object which includes a small number of
named methods such as `OrderedProperties.items()`
and `OrderedProperties.values()`.  When
accessing attributes dynamically, favor using the dict-access
scheme, e.g. `mapper.relationships[somename]` over
`getattr(mapper.relationships, somename)` to avoid name
collisions.

See also

[Mapper.attrs](#sqlalchemy.orm.Mapper.attrs) - namespace of all
[MapperProperty](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.MapperProperty)
objects.

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

The `FromClause` construct this
[Mapper](#sqlalchemy.orm.Mapper) selects from by default.

Normally, this is equivalent to [persist_selectable](#sqlalchemy.orm.Mapper.persist_selectable), unless
the `with_polymorphic` feature is in use, in which case the
full “polymorphic” selectable is returned.

    attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)self_and_descendants

The collection including this mapper and all descendant mappers.

This includes not just the immediately inheriting mappers but
all their inheriting mappers as well.

    attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)single: bool

Represent `True` if this [Mapper](#sqlalchemy.orm.Mapper) is a single table
inheritance mapper.

[Mapper.local_table](#sqlalchemy.orm.Mapper.local_table) will be `None` if this flag is set.

This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.

    attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)synonyms

Return a namespace of all [Synonym](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.Synonym)
properties maintained by this [Mapper](#sqlalchemy.orm.Mapper).

See also

[Mapper.attrs](#sqlalchemy.orm.Mapper.attrs) - namespace of all
[MapperProperty](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.MapperProperty)
objects.

     attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)tables: [Sequence](https://docs.sqlalchemy.org/en/20/core/defaults.html#sqlalchemy.schema.Sequence)[[TableClause](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.TableClause)]

A sequence containing the collection of [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table)
or `TableClause` objects which this [Mapper](#sqlalchemy.orm.Mapper)
is aware of.

If the mapper is mapped to a [Join](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.Join), or an
[Alias](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.Alias)
representing a [Select](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.Select), the individual
[Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table)
objects that comprise the full construct will be represented here.

This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.

    attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)validators: util.immutabledict[str, [Tuple](https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.Tuple)[str, Dict[str, Any]]]

An immutable dictionary of attributes which have been decorated
using the [validates()](https://docs.sqlalchemy.org/en/20/orm/mapped_attributes.html#sqlalchemy.orm.validates) decorator.

The dictionary contains string attribute names as keys
mapped to the actual validation method.

    attribute [sqlalchemy.orm.Mapper.](#sqlalchemy.orm.Mapper)with_polymorphic_mappers

The list of [Mapper](#sqlalchemy.orm.Mapper) objects included in the
default “polymorphic” query.

     function sqlalchemy.orm.object_mapper(*instance:_T*) → [Mapper](#sqlalchemy.orm.Mapper)[_T]

Given an object, return the primary Mapper associated with the object
instance.

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

This function is available via the inspection system as:

```
inspect(instance).mapper
```

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.orm_insert_sentinel(*name:str|None=None*, *type_:_TypeEngineArgument[Any]|None=None*, ***, *default:Any|None=None*, *omit_from_statements:bool=True*) → [MappedColumn](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.MappedColumn)[Any]

Provides a surrogate [mapped_column()](#sqlalchemy.orm.mapped_column) that generates
a so-called [sentinel](https://docs.sqlalchemy.org/en/20/glossary.html#term-sentinel) column, allowing efficient bulk
inserts with deterministic RETURNING sorting for tables that don’t
otherwise have qualifying primary key configurations.

Use of [orm_insert_sentinel()](#sqlalchemy.orm.orm_insert_sentinel) is analogous to the use of the
[insert_sentinel()](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.insert_sentinel) construct within a Core
[Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) construct.

Guidelines for adding this construct to a Declarative mapped class
are the same as that of the [insert_sentinel()](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.insert_sentinel) construct;
the database table itself also needs to have a column with this name
present.

For background on how this object is used, see the section
[Configuring Sentinel Columns](https://docs.sqlalchemy.org/en/20/core/connections.html#engine-insertmanyvalues-sentinel-columns) as part of the
section [“Insert Many Values” Behavior for INSERT statements](https://docs.sqlalchemy.org/en/20/core/connections.html#engine-insertmanyvalues).

See also

[insert_sentinel()](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.insert_sentinel)

[“Insert Many Values” Behavior for INSERT statements](https://docs.sqlalchemy.org/en/20/core/connections.html#engine-insertmanyvalues)

[Configuring Sentinel Columns](https://docs.sqlalchemy.org/en/20/core/connections.html#engine-insertmanyvalues-sentinel-columns)

Added in version 2.0.10.

     function sqlalchemy.orm.polymorphic_union(*table_map*, *typecolname*, *aliasname='p_union'*, *cast_nulls=True*)

Create a `UNION` statement used by a polymorphic mapper.

See  [Concrete Table Inheritance](https://docs.sqlalchemy.org/en/20/orm/inheritance.html#concrete-inheritance) for an example of how
this is used.

  Parameters:

- **table_map** – mapping of polymorphic identities to
  [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) objects.
- **typecolname** – string name of a “discriminator” column, which will be
  derived from the query, producing the polymorphic identity for
  each row.  If `None`, no polymorphic discriminator is generated.
- **aliasname** – name of the [alias()](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.alias)
  construct generated.
- **cast_nulls** – if True, non-existent columns, which are represented
  as labeled NULLs, will be passed into CAST.   This is a legacy behavior
  that is problematic on some backends such as Oracle - in which case it
  can be set to False.

      function sqlalchemy.orm.reconstructor(*fn:_Fn*) → _Fn

Decorate a method as the ‘reconstructor’ hook.

Designates a single method as the “reconstructor”, an `__init__`-like
method that will be called by the ORM after the instance has been
loaded from the database or otherwise reconstituted.

Tip

The [reconstructor()](#sqlalchemy.orm.reconstructor) decorator makes use of the
[InstanceEvents.load()](https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.InstanceEvents.load) event hook, which can be
used directly.

The reconstructor will be invoked with no arguments.  Scalar
(non-collection) database-mapped attributes of the instance will
be available for use within the function.  Eagerly-loaded
collections are generally not yet available and will usually only
contain the first element.  ORM state changes made to objects at
this stage will not be recorded for the next flush() operation, so
the activity within a reconstructor should be conservative.

See also

[InstanceEvents.load()](https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.InstanceEvents.load)

     class sqlalchemy.orm.registry

Generalized registry for mapping classes.

The [registry](#sqlalchemy.orm.registry) serves as the basis for maintaining a collection
of mappings, and provides configurational hooks used to map classes.

The three general kinds of mappings supported are Declarative Base,
Declarative Decorator, and Imperative Mapping.   All of these mapping
styles may be used interchangeably:

- [registry.generate_base()](#sqlalchemy.orm.registry.generate_base) returns a new declarative base
  class, and is the underlying implementation of the
  [declarative_base()](#sqlalchemy.orm.declarative_base) function.
- [registry.mapped()](#sqlalchemy.orm.registry.mapped) provides a class decorator that will
  apply declarative mapping to a class without the use of a declarative
  base class.
- [registry.map_imperatively()](#sqlalchemy.orm.registry.map_imperatively) will produce a
  [Mapper](#sqlalchemy.orm.Mapper) for a class without scanning the class for
  declarative class attributes. This method suits the use case historically
  provided by the `sqlalchemy.orm.mapper()` classical mapping function,
  which is removed as of SQLAlchemy 2.0.

Added in version 1.4.

See also

[ORM Mapped Class Overview](https://docs.sqlalchemy.org/en/20/orm/mapping_styles.html) - overview of class mapping
styles.

| Member Name | Description |
| --- | --- |
| __init__() | Construct a newregistry |
| as_declarative_base() | Class decorator which will invokeregistry.generate_base()for a given base class. |
| configure() | Configure all as-yet unconfigured mappers in thisregistry. |
| dispose() | Dispose of all mappers in thisregistry. |
| generate_base() | Generate a declarative base class. |
| map_declaratively() | Map a class declaratively. |
| map_imperatively() | Map a class imperatively. |
| mapped() | Class decorator that will apply the Declarative mapping process
to a given class. |
| mapped_as_dataclass() | Class decorator that will apply the Declarative mapping process
to a given class, and additionally convert the class to be a
Python dataclass. |
| update_type_annotation_map() | update theregistry.type_annotation_mapwith new
values. |

   method [sqlalchemy.orm.registry.](#sqlalchemy.orm.registry)__init__(***, *metadata:MetaData|None=None*, *class_registry:clsregistry._ClsRegistryType|None=None*, *type_annotation_map:_TypeAnnotationMapType|None=None*, *constructor:Callable[...*, *None]=<function_declarative_constructor>*)

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

  Parameters:

- **metadata** – An optional [MetaData](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.MetaData) instance.  All
  [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) objects generated using declarative
  table mapping will make use of this [MetaData](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.MetaData)
  collection.  If this argument is left at its default of `None`,
  a blank [MetaData](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.MetaData) collection is created.
- **constructor** – Specify the implementation for the `__init__` function on a mapped
  class that has no `__init__` of its own.  Defaults to an
  implementation that assigns **kwargs for declared
  fields and relationships to an instance.  If `None` is supplied,
  no __init__ will be provided and construction will fall back to
  cls.__init__ by way of the normal Python semantics.
- **class_registry** – optional dictionary that will serve as the
  registry of class names-> mapped classes when string names
  are used to identify classes inside of [relationship()](https://docs.sqlalchemy.org/en/20/orm/relationship_api.html#sqlalchemy.orm.relationship)
  and others.  Allows two or more declarative base classes
  to share the same registry of class names for simplified
  inter-base relationships.
- **type_annotation_map** –
  optional dictionary of Python types to
  SQLAlchemy [TypeEngine](https://docs.sqlalchemy.org/en/20/core/type_api.html#sqlalchemy.types.TypeEngine) classes or instances.
  The provided dict will update the default type mapping.  This
  is used exclusively by the [MappedColumn](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.MappedColumn) construct
  to produce column types based on annotations within the
  [Mapped](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.Mapped) type.
  Added in version 2.0.
  See also
  [Customizing the Type Map](https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#orm-declarative-mapped-column-type-map)

      method [sqlalchemy.orm.registry.](#sqlalchemy.orm.registry)as_declarative_base(***kw:Any*) → Callable[[Type[_T]], Type[_T]]

Class decorator which will invoke
[registry.generate_base()](#sqlalchemy.orm.registry.generate_base)
for a given base class.

E.g.:

```
from sqlalchemy.orm import registry

mapper_registry = registry()

@mapper_registry.as_declarative_base()
class Base:
    @declared_attr
    def __tablename__(cls):
        return cls.__name__.lower()

    id = Column(Integer, primary_key=True)

class MyMappedClass(Base): ...
```

All keyword arguments passed to
[registry.as_declarative_base()](#sqlalchemy.orm.registry.as_declarative_base) are passed
along to [registry.generate_base()](#sqlalchemy.orm.registry.generate_base).

    method [sqlalchemy.orm.registry.](#sqlalchemy.orm.registry)configure(*cascade:bool=False*) → None

Configure all as-yet unconfigured mappers in this
[registry](#sqlalchemy.orm.registry).

The configure step is used to reconcile and initialize the
[relationship()](https://docs.sqlalchemy.org/en/20/orm/relationship_api.html#sqlalchemy.orm.relationship) linkages between mapped classes, as well as
to invoke configuration events such as the
[MapperEvents.before_configured()](https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.MapperEvents.before_configured) and
[MapperEvents.after_configured()](https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.MapperEvents.after_configured), which may be used by ORM
extensions or user-defined extension hooks.

If one or more mappers in this registry contain
[relationship()](https://docs.sqlalchemy.org/en/20/orm/relationship_api.html#sqlalchemy.orm.relationship) constructs that refer to mapped classes in
other registries, this registry is said to be *dependent* on those
registries. In order to configure those dependent registries
automatically, the [configure.cascade](#sqlalchemy.orm.registry.configure.params.cascade) flag
should be set to `True`. Otherwise, if they are not configured, an
exception will be raised.  The rationale behind this behavior is to
allow an application to programmatically invoke configuration of
registries while controlling whether or not the process implicitly
reaches other registries.

As an alternative to invoking [registry.configure()](#sqlalchemy.orm.registry.configure), the ORM
function [configure_mappers()](#sqlalchemy.orm.configure_mappers) function may be used to ensure
configuration is complete for all [registry](#sqlalchemy.orm.registry) objects in
memory. This is generally simpler to use and also predates the usage of
[registry](#sqlalchemy.orm.registry) objects overall. However, this function will
impact all mappings throughout the running Python process and may be
more memory/time consuming for an application that has many registries
in use for different purposes that may not be needed immediately.

See also

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

Added in version 1.4.0b2.

     method [sqlalchemy.orm.registry.](#sqlalchemy.orm.registry)dispose(*cascade:bool=False*) → None

Dispose of all mappers in this [registry](#sqlalchemy.orm.registry).

After invocation, all the classes that were mapped within this registry
will no longer have class instrumentation associated with them. This
method is the per-[registry](#sqlalchemy.orm.registry) analogue to the
application-wide [clear_mappers()](#sqlalchemy.orm.clear_mappers) function.

If this registry contains mappers that are dependencies of other
registries, typically via [relationship()](https://docs.sqlalchemy.org/en/20/orm/relationship_api.html#sqlalchemy.orm.relationship) links, then those
registries must be disposed as well. When such registries exist in
relation to this one, their [registry.dispose()](#sqlalchemy.orm.registry.dispose) method will
also be called, if the [dispose.cascade](#sqlalchemy.orm.registry.dispose.params.cascade) flag
is set to `True`; otherwise, an error is raised if those registries
were not already disposed.

Added in version 1.4.0b2.

See also

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

     method [sqlalchemy.orm.registry.](#sqlalchemy.orm.registry)generate_base(*mapper:~typing.Callable[[...],~sqlalchemy.orm.mapper.Mapper[~typing.Any]]|None=None,cls:~typing.Type[~typing.Any]=<class'object'>,name:str='Base',metaclass:~typing.Type[~typing.Any]=<class'sqlalchemy.orm.decl_api.DeclarativeMeta'>*) → Any

Generate a declarative base class.

Classes that inherit from the returned class object will be
automatically mapped using declarative mapping.

E.g.:

```
from sqlalchemy.orm import registry

mapper_registry = registry()

Base = mapper_registry.generate_base()

class MyClass(Base):
    __tablename__ = "my_table"
    id = Column(Integer, primary_key=True)
```

The above dynamically generated class is equivalent to the
non-dynamic example below:

```
from sqlalchemy.orm import registry
from sqlalchemy.orm.decl_api import DeclarativeMeta

mapper_registry = registry()

class Base(metaclass=DeclarativeMeta):
    __abstract__ = True
    registry = mapper_registry
    metadata = mapper_registry.metadata

    __init__ = mapper_registry.constructor
```

Changed in version 2.0: Note that the
[registry.generate_base()](#sqlalchemy.orm.registry.generate_base) method is superseded by the new
[DeclarativeBase](#sqlalchemy.orm.DeclarativeBase) class, which generates a new “base”
class using subclassing, rather than return value of a function.
This allows an approach that is compatible with [PEP 484](https://peps.python.org/pep-0484/) typing
tools.

The [registry.generate_base()](#sqlalchemy.orm.registry.generate_base) method provides the
implementation for the [declarative_base()](#sqlalchemy.orm.declarative_base) function, which
creates the [registry](#sqlalchemy.orm.registry) and base class all at once.

See the section [Declarative Mapping](https://docs.sqlalchemy.org/en/20/orm/mapping_styles.html#orm-declarative-mapping) for background and
examples.

  Parameters:

- **mapper** – An optional callable, defaults to [Mapper](#sqlalchemy.orm.Mapper).
  This function is used to generate new [Mapper](#sqlalchemy.orm.Mapper) objects.
- **cls** – Defaults to `object`. A type to use as the base for the
  generated declarative base class. May be a class or tuple of classes.
- **name** – Defaults to `Base`.  The display name for the generated
  class.  Customizing this is not required, but can improve clarity in
  tracebacks and debugging.
- **metaclass** – Defaults to `DeclarativeMeta`.  A metaclass or __metaclass__
  compatible callable to use as the meta type of the generated
  declarative base class.

See also

[Declarative Mapping](https://docs.sqlalchemy.org/en/20/orm/mapping_styles.html#orm-declarative-mapping)

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

     method [sqlalchemy.orm.registry.](#sqlalchemy.orm.registry)map_declaratively(*cls:Type[_O]*) → [Mapper](#sqlalchemy.orm.Mapper)[_O]

Map a class declaratively.

In this form of mapping, the class is scanned for mapping information,
including for columns to be associated with a table, and/or an
actual table object.

Returns the [Mapper](#sqlalchemy.orm.Mapper) object.

E.g.:

```
from sqlalchemy.orm import registry

mapper_registry = registry()

class Foo:
    __tablename__ = "some_table"

    id = Column(Integer, primary_key=True)
    name = Column(String)

mapper = mapper_registry.map_declaratively(Foo)
```

This function is more conveniently invoked indirectly via either the
[registry.mapped()](#sqlalchemy.orm.registry.mapped) class decorator or by subclassing a
declarative metaclass generated from
[registry.generate_base()](#sqlalchemy.orm.registry.generate_base).

See the section [Declarative Mapping](https://docs.sqlalchemy.org/en/20/orm/mapping_styles.html#orm-declarative-mapping) for complete
details and examples.

  Parameters:

**cls** – class to be mapped.

  Returns:

a [Mapper](#sqlalchemy.orm.Mapper) object.

See also

[Declarative Mapping](https://docs.sqlalchemy.org/en/20/orm/mapping_styles.html#orm-declarative-mapping)

[registry.mapped()](#sqlalchemy.orm.registry.mapped) - more common decorator interface
to this function.

[registry.map_imperatively()](#sqlalchemy.orm.registry.map_imperatively)

     method [sqlalchemy.orm.registry.](#sqlalchemy.orm.registry)map_imperatively(*class_:Type[_O]*, *local_table:FromClause|None=None*, ***kw:Any*) → [Mapper](#sqlalchemy.orm.Mapper)[_O]

Map a class imperatively.

In this form of mapping, the class is not scanned for any mapping
information.  Instead, all mapping constructs are passed as
arguments.

This method is intended to be fully equivalent to the now-removed
SQLAlchemy `mapper()` function, except that it’s in terms of
a particular registry.

E.g.:

```
from sqlalchemy.orm import registry

mapper_registry = registry()

my_table = Table(
    "my_table",
    mapper_registry.metadata,
    Column("id", Integer, primary_key=True),
)

class MyClass:
    pass

mapper_registry.map_imperatively(MyClass, my_table)
```

See the section [Imperative Mapping](https://docs.sqlalchemy.org/en/20/orm/mapping_styles.html#orm-imperative-mapping) for complete background
and usage examples.

  Parameters:

- **class_** – The class to be mapped.  Corresponds to the
  [Mapper.class_](#sqlalchemy.orm.Mapper.params.class_) parameter.
- **local_table** – the [Table](https://docs.sqlalchemy.org/en/20/core/metadata.html#sqlalchemy.schema.Table) or other
  [FromClause](https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.FromClause) object that is the subject of the mapping.
  Corresponds to the
  [Mapper.local_table](#sqlalchemy.orm.Mapper.params.local_table) parameter.
- ****kw** – all other keyword arguments are passed to the
  [Mapper](#sqlalchemy.orm.Mapper) constructor directly.

See also

[Imperative Mapping](https://docs.sqlalchemy.org/en/20/orm/mapping_styles.html#orm-imperative-mapping)

[Declarative Mapping](https://docs.sqlalchemy.org/en/20/orm/mapping_styles.html#orm-declarative-mapping)

     method [sqlalchemy.orm.registry.](#sqlalchemy.orm.registry)mapped(*cls:Type[_O]*) → Type[_O]

Class decorator that will apply the Declarative mapping process
to a given class.

E.g.:

```
from sqlalchemy.orm import registry

mapper_registry = registry()

@mapper_registry.mapped
class Foo:
    __tablename__ = "some_table"

    id = Column(Integer, primary_key=True)
    name = Column(String)
```

See the section [Declarative Mapping](https://docs.sqlalchemy.org/en/20/orm/mapping_styles.html#orm-declarative-mapping) for complete
details and examples.

  Parameters:

**cls** – class to be mapped.

  Returns:

the class that was passed.

See also

[Declarative Mapping](https://docs.sqlalchemy.org/en/20/orm/mapping_styles.html#orm-declarative-mapping)

[registry.generate_base()](#sqlalchemy.orm.registry.generate_base) - generates a base class
that will apply Declarative mapping to subclasses automatically
using a Python metaclass.

See also

[registry.mapped_as_dataclass()](#sqlalchemy.orm.registry.mapped_as_dataclass)

     method [sqlalchemy.orm.registry.](#sqlalchemy.orm.registry)mapped_as_dataclass(*_registry__cls:Type[_O]|None=None*, ***, *init:_NoArg|bool=_NoArg.NO_ARG*, *repr:_NoArg|bool=_NoArg.NO_ARG*, *eq:_NoArg|bool=_NoArg.NO_ARG*, *order:_NoArg|bool=_NoArg.NO_ARG*, *unsafe_hash:_NoArg|bool=_NoArg.NO_ARG*, *match_args:_NoArg|bool=_NoArg.NO_ARG*, *kw_only:_NoArg|bool=_NoArg.NO_ARG*, *dataclass_callable:_NoArg|Callable[...,Type[Any]]=_NoArg.NO_ARG*) → Type[_O] | Callable[[Type[_O]], Type[_O]]

Class decorator that will apply the Declarative mapping process
to a given class, and additionally convert the class to be a
Python dataclass.

See also

[Declarative Dataclass Mapping](https://docs.sqlalchemy.org/en/20/orm/dataclasses.html#orm-declarative-native-dataclasses) - complete background
on SQLAlchemy native dataclass mapping

[mapped_as_dataclass()](#sqlalchemy.orm.mapped_as_dataclass) - functional version that may
provide better compatibility with mypy

Added in version 2.0.

     property mappers: FrozenSet[[Mapper](#sqlalchemy.orm.Mapper)[Any]]

read only collection of all [Mapper](#sqlalchemy.orm.Mapper) objects.

    method [sqlalchemy.orm.registry.](#sqlalchemy.orm.registry)update_type_annotation_map(*type_annotation_map:_TypeAnnotationMapType*) → None

update the [registry.type_annotation_map](#sqlalchemy.orm.registry.params.type_annotation_map) with new
values.

     function sqlalchemy.orm.synonym_for(*name:str*, *map_column:bool=False*) → Callable[[Callable[[...], Any]], [Synonym](https://docs.sqlalchemy.org/en/20/orm/internals.html#sqlalchemy.orm.Synonym)[Any]]

Decorator that produces an [synonym()](https://docs.sqlalchemy.org/en/20/orm/mapped_attributes.html#sqlalchemy.orm.synonym)
attribute in conjunction with a Python descriptor.

The function being decorated is passed to [synonym()](https://docs.sqlalchemy.org/en/20/orm/mapped_attributes.html#sqlalchemy.orm.synonym) as the
[synonym.descriptor](https://docs.sqlalchemy.org/en/20/orm/mapped_attributes.html#sqlalchemy.orm.synonym.params.descriptor) parameter:

```
class MyClass(Base):
    __tablename__ = "my_table"

    id = Column(Integer, primary_key=True)
    _job_status = Column("job_status", String(50))

    @synonym_for("job_status")
    @property
    def job_status(self):
        return "Status: %s" % self._job_status
```

The [hybrid properties](https://docs.sqlalchemy.org/en/20/orm/mapped_attributes.html#mapper-hybrids) feature of SQLAlchemy
is typically preferred instead of synonyms, which is a more legacy
feature.

See also

[Synonyms](https://docs.sqlalchemy.org/en/20/orm/mapped_attributes.html#synonyms) - Overview of synonyms

[synonym()](https://docs.sqlalchemy.org/en/20/orm/mapped_attributes.html#sqlalchemy.orm.synonym) - the mapper-level function

[Using Descriptors and Hybrids](https://docs.sqlalchemy.org/en/20/orm/mapped_attributes.html#mapper-hybrids) - The Hybrid Attribute extension provides an
updated approach to augmenting attribute behavior more flexibly than
can be achieved with synonyms.
