sqlalchemy.orm.attributes InstrumentedAttribute Example Code

InstrumentedAttribute is a class within the sqlalchemy.orm.attributes module of the SQLAlchemy project.

QueryableAttribute and flag_modified are a couple of other callables within the sqlalchemy.orm.attributes package that also have code examples.

Example 1 from SQLAlchemy Mixins

SQLAlchemy Mixins (PyPI package information) is a collection of mixins useful for extending SQLAlchemy and simplifying your database-interacting code for some common use cases. SQLAlchemy Mixins is open sourced under the MIT license.

SQLAlchemy Mixins / sqlalchemy_mixins / eagerload.py

# eagerload.py
try:
    from typing import List
except ImportError: # pragma: no cover
    pass

from sqlalchemy.orm import joinedload
from sqlalchemy.orm import subqueryload
from sqlalchemy.orm.attributes import InstrumentedAttribute

from .session import SessionMixin

JOINED = 'joined'
SUBQUERY = 'subquery'


def eager_expr(schema):
    flat_schema = _flatten_schema(schema)
    return _eager_expr_from_flat_schema(flat_schema)


def _flatten_schema(schema):
    def _flatten(schema, parent_path, result):
        for path, value in schema.items():
            if isinstance(path, InstrumentedAttribute):
                path = path.key

            if isinstance(value, tuple):
                join_method, inner_schema = value[0], value[1]
            elif isinstance(value, dict):
                join_method, inner_schema = JOINED, value
            else:
                join_method, inner_schema = value, None

            full_path = parent_path + '.' + path if parent_path else path
            result[full_path] = join_method

            if inner_schema:
                _flatten(inner_schema, full_path, result)

    result = {}
    _flatten(schema, '', result)
    return result


def _eager_expr_from_flat_schema(flat_schema):
    result = []
    for path, join_method in flat_schema.items():
        if join_method == JOINED:


## ... source file continues with no further InstrumentedAttribute examples...

Example 2 from sqlalchemy-utils

sqlalchemy-utils (project documentation and PyPI package information) is a code library with various helper functions and new data types that make it easier to use SQLAlchemy when building projects that involve more specific storage requirements such as currency. The wide array of data types includes ranged values and aggregated attributes.

sqlalchemy-utils / sqlalchemy_utils / path.py

# path.py
import sqlalchemy as sa
from sqlalchemy.orm.attributes import InstrumentedAttribute
from sqlalchemy.util.langhelpers import symbol

from .utils import str_coercible


@str_coercible
class Path(object):
    def __init__(self, path, separator='.'):
        if isinstance(path, Path):
            self.path = path.path
        else:
            self.path = path
        self.separator = separator

    @property
    def parts(self):
        return self.path.split(self.separator)

    def __iter__(self):
        for part in self.parts:
            yield part

    def __len__(self):
        return len(self.parts)


## ... source file abbreviated to get to InstrumentedAttribute examples ...


        return "%s('%s')" % (self.__class__.__name__, self.path)

    def index(self, element):
        return self.parts.index(element)

    def __getitem__(self, slice):
        result = self.parts[slice]
        if isinstance(result, list):
            return self.__class__(
                self.separator.join(result),
                separator=self.separator
            )
        return result

    def __eq__(self, other):
        return self.path == other.path and self.separator == other.separator

    def __ne__(self, other):
        return not (self == other)

    def __unicode__(self):
        return self.path


def get_attr(mixed, attr):
    if isinstance(mixed, InstrumentedAttribute):
        return getattr(
            mixed.property.mapper.class_,
            attr
        )
    else:
        return getattr(mixed, attr)


@str_coercible
class AttrPath(object):
    def __init__(self, class_, path):
        self.class_ = class_
        self.path = Path(path)
        self.parts = []
        last_attr = class_
        for value in self.path:
            last_attr = get_attr(last_attr, value)
            self.parts.append(last_attr)

    def __iter__(self):
        for part in self.parts:
            yield part

    def __invert__(self):


## ... source file continues with no further InstrumentedAttribute examples...

Example 3 from WTForms-Alchemy

wtforms-alchemy (documentation and PyPI package information) is a WTForms extension toolkit for easier creation of SQLAlchemy model based forms. While this project primarily focuses on proper form handling, it also has many good examples of how to use various parts of SQLAlchemy in its code base. The project is provided as open source under the MIT license.

WTForms-Alchemy / wtforms_alchemy / validators.py

# validators.py
from collections.abc import Iterable, Mapping

import six
from sqlalchemy import Column
from sqlalchemy.orm.attributes import InstrumentedAttribute
from wtforms import ValidationError


class Unique(object):
    field_flags = ('unique', )

    def __init__(self, column, get_session=None, message=None):
        self.column = column
        self.message = message
        self.get_session = get_session

    @property
    def query(self):
        self._check_for_session(self.model)
        if self.get_session:
            return self.get_session().query(self.model)
        elif hasattr(self.model, 'query'):
            return getattr(self.model, 'query')
        else:
            raise Exception(
                'Validator requires either get_session or Flask-SQLAlchemy'
                ' styled query parameter'
            )



## ... source file continues with no further InstrumentedAttribute examples...
1. Introduction 2. Development Environments 3. Data 4. Web Development 5. Deployment 6. DevOps Changelog What Full Stack Means About the Author Future Directions Page Statuses SQLAlchemy ExtensionsSQLAlchemy Example CodeSQLAlchemy Modelssqlalchemy.databases mysqlsqlalchemy.dialects mssqlsqlalchemy.dialects mysqlsqlalchemy.dialects oraclesqlalchemy.schema DDLsqlalchemy.dialects postgresqlsqlalchemy.sql.expression Functionsqlalchemy.dialects sqlitesqlalchemy.dialects.mysql pymysqlsqlalchemy.dialects.postgresql ARRAYsqlalchemy.dialects.postgresql BIGINTsqlalchemy.dialects.postgresql BITsqlalchemy.dialects.postgresql DOUBLE_PRECISIONsqlalchemy.dialects.postgresql ExcludeConstraintsqlalchemy.dialects.postgresql INTEGERsqlalchemy.dialects.postgresql JSONsqlalchemy.dialects.postgresql TSVECTORsqlalchemy.dialects.postgresql pypostgresqlsqlalchemy.dialects.postgresql.base PGCompilersqlalchemy.dialects.postgresql.base PGIdentifierPreparersqlalchemy.dialects.postgresql.base PGTypeCompilersqlalchemy.dialects.postgresql.psycopg2 PGDialect_psycopg2sqlalchemy.dialects.sqlite pysqlitesqlalchemy.engine Connectionsqlalchemy.engine Enginesqlalchemy.engine create_enginesqlalchemy.engine defaultsqlalchemy.engine urlsqlalchemy.engine.default DefaultDialectsqlalchemy.engine.interfaces ExecutionContextsqlalchemy.engine.result ResultMetaDatasqlalchemy.engine.result RowProxysqlalchemy.engine.strategies EngineStrategysqlalchemy.engine.strategies MockEngineStrategysqlalchemy.engine.url make_urlsqlalchemy.events SchemaEventTargetsqlalchemy.exc ArgumentErrorsqlalchemy.exc DataErrorsqlalchemy.exc DatabaseErrorsqlalchemy.exc IntegrityErrorsqlalchemy.exc InvalidRequestErrorsqlalchemy.exc NoInspectionAvailablesqlalchemy.exc NoSuchTableErrorsqlalchemy.exc OperationalErrorsqlalchemy.exc ProgrammingErrorsqlalchemy.exc UnsupportedCompilationErrorsqlalchemy.ext compilersqlalchemy.ext.associationproxy AssociationProxysqlalchemy.ext.automap automap_basesqlalchemy.ext.compiler compilessqlalchemy.ext.declarative DeclarativeMetasqlalchemy.ext.declarative declarative_basesqlalchemy.ext.hybrid hybrid_methodsqlalchemy.ext.hybrid hybrid_propertysqlalchemy.ext.mutable Mutablesqlalchemy.inspection inspectsqlalchemy.orm ColumnPropertysqlalchemy.orm CompositePropertysqlalchemy.orm Loadsqlalchemy.orm Querysqlalchemy.orm RelationshipPropertysqlalchemy.orm SynonymPropertysqlalchemy.orm aliasedsqlalchemy.orm attributessqlalchemy.orm backrefsqlalchemy.orm class_mappersqlalchemy.orm column_propertysqlalchemy.orm compositesqlalchemy.orm interfacessqlalchemy.orm mappersqlalchemy.orm mapperlibsqlalchemy.orm object_mappersqlalchemy.orm object_sessionsqlalchemy.orm relationshipsqlalchemy.orm sessionsqlalchemy.orm sessionmakersqlalchemy.orm strategiessqlalchemy.orm.attributes InstrumentedAttributesqlalchemy.orm.attributes QueryableAttributesqlalchemy.orm.attributes flag_modifiedsqlalchemy.orm.collections InstrumentedListsqlalchemy.orm.exc NoResultFoundsqlalchemy.orm.exc UnmappedClassErrorsqlalchemy.orm.exc UnmappedInstanceErrorsqlalchemy.orm.interfaces MapperPropertysqlalchemy.orm.interfaces PropComparatorsqlalchemy.orm.mapper Mappersqlalchemy.orm.properties ColumnPropertysqlalchemy.orm.properties RelationshipPropertysqlalchemy.orm.query Querysqlalchemy.orm.query QueryContextsqlalchemy.orm.relationships RelationshipPropertysqlalchemy.orm.session Sessionsqlalchemy.orm.session object_sessionsqlalchemy.orm.util AliasedClasssqlalchemy.orm.util AliasedInspsqlalchemy.orm.util identity_keysqlalchemy.pool NullPoolsqlalchemy.pool StaticPoolsqlalchemy.schema CheckConstraintsqlalchemy.schema Columnsqlalchemy.schema CreateIndexsqlalchemy.schema CreateTablesqlalchemy.schema DDLElementsqlalchemy.schema ForeignKeysqlalchemy.schema ForeignKeyConstraintsqlalchemy.schema Indexsqlalchemy.schema PrimaryKeyConstraintsqlalchemy.schema Tablesqlalchemy.sql ClauseElementsqlalchemy.sql columnsqlalchemy.sql expressionsqlalchemy.sql extractsqlalchemy.sql functionssqlalchemy.sql operatorssqlalchemy.sql schemasqlalchemy.sql selectsqlalchemy.sql sqltypessqlalchemy.sql tablesqlalchemy.sql.compiler SQLCompilersqlalchemy.sql.elements ColumnElementsqlalchemy.sql.elements Labelsqlalchemy.sql.expression ClauseElementsqlalchemy.sql.expression ColumnClausesqlalchemy.sql.expression ColumnElementsqlalchemy.sql.expression Executablesqlalchemy.sql.expression FunctionElementsqlalchemy.sql.expression UnaryExpressionsqlalchemy.sql.functions FunctionElementsqlalchemy.sql.functions GenericFunctionsqlalchemy.sql.naming convsqlalchemy.sql.schema Columnsqlalchemy.sql.schema SchemaItemsqlalchemy.sql.sqltypes NullTypesqlalchemy.sql.util ClauseAdaptersqlalchemy.sql.visitors traversesqlalchemy.types Booleansqlalchemy.types Datesqlalchemy.types DateTimesqlalchemy.types Enumsqlalchemy.types Floatsqlalchemy.types Integersqlalchemy.types Intervalsqlalchemy.types NULLTYPEsqlalchemy.types Stringsqlalchemy.types Textsqlalchemy.types Timesqlalchemy.types TypeEnginesqlalchemy.types UserDefinedTypesqlalchemy.types to_instancesqlalchemy.util OrderedDictsqlalchemy.util OrderedSetsqlalchemy.util set_creation_ordersqlalchemy.util symbolsqlalchemy.util topologicalsqlalchemy.util.langhelpers public_factorysqlalchemy.util.langhelpers symbol ...or view the full table of contents.

Full Stack Python

Full Stack Python is an open book that explains concepts in plain language and provides helpful resources for those topics.
Updates via Twitter & Facebook.

Matt Makai 2012-2022