class documentation

class TypeDecorator(ExternalType, SchemaEventTarget, TypeEngine):

Known subclasses: sqlalchemy.sql.type_api.Variant, sqlalchemy.types.Interval, sqlalchemy.types.PickleType, sqlalchemy.dialects.mssql.information_schema.CoerceUnicode, sqlalchemy.dialects.mssql.information_schema.IdentitySqlVariant

View In Hierarchy

Allows the creation of types which add additional functionality to an existing type.

This method is preferred to direct subclassing of SQLAlchemy's built-in types as it ensures that all required functionality of the underlying type is kept in place.

Typical usage:

import sqlalchemy.types as types

class MyType(types.TypeDecorator):
    '''Prefixes Unicode values with "PREFIX:" on the way in and
    strips it off on the way out.
    '''

    impl = types.Unicode

    cache_ok = True

    def process_bind_param(self, value, dialect):
        return "PREFIX:" + value

    def process_result_value(self, value, dialect):
        return value[7:]

    def copy(self, **kw):
        return MyType(self.impl.length)

The class-level impl attribute is required, and can reference any .TypeEngine class. Alternatively, the load_dialect_impl method can be used to provide different type classes based on the dialect given; in this case, the impl variable can reference TypeEngine as a placeholder.

The .TypeDecorator.cache_ok class-level flag indicates if this custom .TypeDecorator is safe to be used as part of a cache key. This flag defaults to None which will initially generate a warning when the SQL compiler attempts to generate a cache key for a statement that uses this type. If the .TypeDecorator is not guaranteed to produce the same bind/result behavior and SQL generation every time, this flag should be set to False; otherwise if the class produces the same behavior each time, it may be set to True. See .TypeDecorator.cache_ok for further notes on how this works.

Types that receive a Python type that isn't similar to the ultimate type used may want to define the TypeDecorator.coerce_compared_value method. This is used to give the expression system a hint when coercing Python objects into bind parameters within expressions. Consider this expression:

mytable.c.somecol + datetime.date(2009, 5, 15)

Above, if "somecol" is an Integer variant, it makes sense that we're doing date arithmetic, where above is usually interpreted by databases as adding a number of days to the given date. The expression system does the right thing by not attempting to coerce the "date()" value into an integer-oriented bind parameter.

However, in the case of TypeDecorator, we are usually changing an incoming Python type to something new - TypeDecorator by default will "coerce" the non-typed side to be the same type as itself. Such as below, we define an "epoch" type that stores a date value as an integer:

class MyEpochType(types.TypeDecorator):
    impl = types.Integer

    epoch = datetime.date(1970, 1, 1)

    def process_bind_param(self, value, dialect):
        return (value - self.epoch).days

    def process_result_value(self, value, dialect):
        return self.epoch + timedelta(days=value)

Our expression of somecol + date with the above type will coerce the "date" on the right side to also be treated as MyEpochType.

This behavior can be overridden via the ~TypeDecorator.coerce_compared_value method, which returns a type that should be used for the value of the expression. Below we set it such that an integer value will be treated as an Integer, and any other value is assumed to be a date and will be treated as a MyEpochType:

def coerce_compared_value(self, op, value):
    if isinstance(value, int):
        return Integer()
    else:
        return self

Warning

Note that the behavior of coerce_compared_value is not inherited by default from that of the base type. If the .TypeDecorator is augmenting a type that requires special logic for certain types of operators, this method must be overridden. A key example is when decorating the _postgresql.JSON and _postgresql.JSONB types; the default rules of .TypeEngine.coerce_compared_value should be used in order to deal with operators like index operations:

class MyJsonType(TypeDecorator):
    impl = postgresql.JSON

    cache_ok = True

    def coerce_compared_value(self, op, value):
        return self.impl.coerce_compared_value(op, value)

Without the above step, index operations such as mycol['foo'] will cause the index value 'foo' to be JSON encoded.

Class ​Comparator A .TypeEngine.Comparator that is specific to .TypeDecorator.
Method __init__ Construct a .TypeDecorator.
Method bind​_expression Given a bind value (i.e. a .BindParameter instance), return a SQL expression which will typically wrap the given parameter.
Method bind​_processor Provide a bound value processing function for the given .Dialect.
Method coerce​_compared​_value Suggest a type for a 'coerced' Python value in an expression.
Method column​_expression Given a SELECT column expression, return a wrapping SQL expression.
Method compare​_values Given two values, compare them for equality.
Method copy Produce a copy of this .TypeDecorator instance.
Method get​_dbapi​_type Return the DBAPI type object represented by this .TypeDecorator.
Method literal​_processor Provide a literal processing function for the given .Dialect.
Method load​_dialect​_impl Return a .TypeEngine object corresponding to a dialect.
Method process​_bind​_param Receive a bound parameter value to be converted.
Method process​_literal​_param Receive a literal parameter value to be rendered inline within a statement.
Method process​_result​_value Receive a result-row column value to be converted.
Method result​_processor Provide a result value processing function for the given .Dialect.
Method type​_engine Return a dialect-specific .TypeEngine instance for this .TypeDecorator.
Class Variable coerce​_to​_is​_types Specify those Python types which should be coerced at the expression level to "IS <constant>" when compared using == (and same for IS NOT in conjunction with !=).
Method __getattr__ Proxy all other undefined accessors to the underlying implementation.
Method __repr__ Undocumented
Method ​_gen​_dialect​_impl #todo
Method ​_set​_parent Support SchemaEventTarget
Method ​_set​_parent​_with​_dispatch Support SchemaEventTarget
Method ​_unwrapped​_dialect​_impl Return the 'unwrapped' dialect impl for this type.
Class Variable __visit​_name__ Undocumented
Class Variable ​_is​_type​_decorator Undocumented
Instance Variable impl Undocumented
Property ​_has​_bind​_expression memoized boolean, check if bind_expression is implemented.
Property ​_has​_bind​_processor memoized boolean, check if process_bind_param is implemented.
Property ​_has​_column​_expression memoized boolean, check if column_expression is implemented.
Property ​_has​_literal​_processor memoized boolean, check if process_literal_param is implemented.
Property ​_has​_result​_processor memoized boolean, check if process_result_value is implemented.
Property ​_type​_affinity #todo
Property comparator​_factory Undocumented
Property sort​_key​_function A sorting function that can be passed as the key to sorted.

Inherited from ExternalType:

Class Variable cache​_ok Indicate if statements using this .ExternalType are "safe to cache".
Property ​_static​_cache​_key Undocumented

Inherited from TypeEngine:

Method adapt Produce an "adapted" form of this type, given an "impl" class to work with.
Method as​_generic Return an instance of the generic type corresponding to this type using heuristic rule. The method may be overridden if this heuristic rule is not sufficient.
Method compare​_against​_backend Compare this type against the given backend type.
Method compile Produce a string-compiled form of this .TypeEngine.
Method dialect​_impl Return a dialect-specific implementation for this .TypeEngine.
Method evaluates​_none Return a copy of this type which has the .should_evaluate_none flag set to True.
Method with​_variant Produce a new type object that will utilize the given type when applied to the dialect of the given name.
Class Variable hashable Flag, if False, means values from this type aren't hashable.
Class Variable should​_evaluate​_none If True, the Python constant None is considered to be handled explicitly by this type.
Static Method ​_to​_instance Undocumented
Method __str__ Undocumented
Method ​_cached​_bind​_processor Return a dialect-specific bind processor for this type.
Method ​_cached​_custom​_processor Undocumented
Method ​_cached​_literal​_processor Return a dialect-specific literal processor for this type.
Method ​_cached​_result​_processor Return a dialect-specific result processor for this type.
Method ​_compare​_type​_affinity Undocumented
Method ​_default​_dialect Undocumented
Method ​_dialect​_info Return a dialect-specific registry which caches a dialect-specific implementation, bind processing function, and one or more result processing functions.
Method ​_resolve​_for​_literal adjust this type given a literal Python value that will be stored in a bound parameter.
Method copy​_value Undocumented
Class Variable ​_is​_array Undocumented
Class Variable ​_is​_table​_value Undocumented
Class Variable ​_is​_tuple​_type Undocumented
Class Variable ​_isnull Undocumented
Class Variable ​_sqla​_type Undocumented
Property ​_generic​_type​_affinity Undocumented
Property ​_static​_cache​_key Undocumented
Property python​_type Return the Python type object expected to be returned by instances of this type, if known.

Inherited from Traversible (via TypeEngine):

Method get​_children Return immediate child .visitors.Traversible elements of this .visitors.Traversible.
Method __class​_getitem__ Undocumented
def __init__(self, *args, **kwargs):

Construct a .TypeDecorator.

Arguments sent here are passed to the constructor of the class assigned to the impl class level attribute, assuming the impl is a callable, and the resulting object is assigned to the self.impl instance attribute (thus overriding the class attribute of the same name).

If the class level impl is not a callable (the unusual case), it will be assigned to the same instance attribute 'as-is', ignoring those arguments passed to the constructor.

Subclasses can override this to customize the generation of self.impl entirely.

def bind_expression(self, bindparam):

Given a bind value (i.e. a .BindParameter instance), return a SQL expression which will typically wrap the given parameter.

Note

This method is called during the SQL compilation phase of a statement, when rendering a SQL string. It is not necessarily called against specific values, and should not be confused with the _types.TypeDecorator.process_bind_param method, which is the more typical method that processes the actual value passed to a particular parameter at statement execution time.

Subclasses of _types.TypeDecorator can override this method to provide custom bind expression behavior for the type. This implementation will replace that of the underlying implementation type.

def bind_processor(self, dialect):

Provide a bound value processing function for the given .Dialect.

This is the method that fulfills the .TypeEngine contract for bound value conversion which normally occurs via the _types.TypeEngine.bind_processor method.

Note

User-defined subclasses of _types.TypeDecorator should not implement this method, and should instead implement _types.TypeDecorator.process_bind_param so that the "inner" processing provided by the implementing type is maintained.

Parameters
dialectDialect instance in use.
def coerce_compared_value(self, op, value):

Suggest a type for a 'coerced' Python value in an expression.

By default, returns self. This method is called by the expression system when an object using this type is on the left or right side of an expression against a plain Python object which does not yet have a SQLAlchemy type assigned:

expr = table.c.somecolumn + 35

Where above, if somecolumn uses this type, this method will be called with the value operator.add and 35. The return value is whatever SQLAlchemy type should be used for 35 for this particular operation.

def column_expression(self, column):

Given a SELECT column expression, return a wrapping SQL expression.

Note

This method is called during the SQL compilation phase of a statement, when rendering a SQL string. It is not called against specific values, and should not be confused with the _types.TypeDecorator.process_result_value method, which is the more typical method that processes the actual value returned in a result row subsequent to statement execution time.

Subclasses of _types.TypeDecorator can override this method to provide custom column expresion behavior for the type. This implementation will replace that of the underlying implementation type.

See the description of _types.TypeEngine.column_expression for a complete description of the method's use.

def compare_values(self, x, y):

Given two values, compare them for equality.

By default this calls upon .TypeEngine.compare_values of the underlying "impl", which in turn usually uses the Python equals operator ==.

This function is used by the ORM to compare an original-loaded value with an intercepted "changed" value, to determine if a net change has occurred.

def copy(self, **kw):

Produce a copy of this .TypeDecorator instance.

This is a shallow copy and is provided to fulfill part of the .TypeEngine contract. It usually does not need to be overridden unless the user-defined .TypeDecorator has local state that should be deep-copied.

def get_dbapi_type(self, dbapi):

Return the DBAPI type object represented by this .TypeDecorator.

By default this calls upon .TypeEngine.get_dbapi_type of the underlying "impl".

def literal_processor(self, dialect):

Provide a literal processing function for the given .Dialect.

This is the method that fulfills the .TypeEngine contract for literal value conversion which normally occurs via the _types.TypeEngine.literal_processor method.

Note

User-defined subclasses of _types.TypeDecorator should not implement this method, and should instead implement _types.TypeDecorator.process_literal_param so that the "inner" processing provided by the implementing type is maintained.

def load_dialect_impl(self, dialect):

Return a .TypeEngine object corresponding to a dialect.

This is an end-user override hook that can be used to provide differing types depending on the given dialect. It is used by the .TypeDecorator implementation of type_engine to help determine what type should ultimately be returned for a given .TypeDecorator.

By default returns self.impl.

def process_bind_param(self, value, dialect):

Receive a bound parameter value to be converted.

Custom subclasses of _types.TypeDecorator should override this method to provide custom behaviors for incoming data values. This method is called at statement execution time and is passed the literal Python data value which is to be associated with a bound parameter in the statement.

The operation could be anything desired to perform custom behavior, such as transforming or serializing data. This could also be used as a hook for validating logic.

See Also

:ref:`types_typedecorator`

_types.TypeDecorator.process_result_value

Parameters
valueData to operate upon, of any type expected by this method in the subclass. Can be None.
dialectthe .Dialect in use.
def process_literal_param(self, value, dialect):

Receive a literal parameter value to be rendered inline within a statement.

Note

This method is called during the SQL compilation phase of a statement, when rendering a SQL string. Unlike other SQL compilation methods, it is passed a specific Python value to be rendered as a string. However it should not be confused with the _types.TypeDecorator.process_bind_param method, which is the more typical method that processes the actual value passed to a particular parameter at statement execution time.

Custom subclasses of _types.TypeDecorator should override this method to provide custom behaviors for incoming data values that are in the special case of being rendered as literals.

The returned string will be rendered into the output string.

def process_result_value(self, value, dialect):

Receive a result-row column value to be converted.

Custom subclasses of _types.TypeDecorator should override this method to provide custom behaviors for data values being received in result rows coming from the database. This method is called at result fetching time and is passed the literal Python data value that's extracted from a database result row.

The operation could be anything desired to perform custom behavior, such as transforming or deserializing data.

See Also

:ref:`types_typedecorator`

_types.TypeDecorator.process_bind_param

Parameters
valueData to operate upon, of any type expected by this method in the subclass. Can be None.
dialectthe .Dialect in use.
def result_processor(self, dialect, coltype):

Provide a result value processing function for the given .Dialect.

This is the method that fulfills the .TypeEngine contract for bound value conversion which normally occurs via the _types.TypeEngine.result_processor method.

Note

User-defined subclasses of _types.TypeDecorator should not implement this method, and should instead implement _types.TypeDecorator.process_result_value so that the "inner" processing provided by the implementing type is maintained.

Parameters
dialectDialect instance in use.
coltypeA SQLAlchemy data type
def type_engine(self, dialect):

Return a dialect-specific .TypeEngine instance for this .TypeDecorator.

In most cases this returns a dialect-adapted form of the .TypeEngine type represented by self.impl. Makes usage of dialect_impl. Behavior can be customized here by overriding load_dialect_impl.

coerce_to_is_types =

Specify those Python types which should be coerced at the expression level to "IS <constant>" when compared using == (and same for IS NOT in conjunction with !=).

For most SQLAlchemy types, this includes NoneType, as well as bool.

.TypeDecorator modifies this list to only include NoneType, as typedecorator implementations that deal with boolean types are common.

Custom .TypeDecorator classes can override this attribute to return an empty tuple, in which case no values will be coerced to constants.

def __getattr__(self, key):
Proxy all other undefined accessors to the underlying implementation.
def __repr__(self):

Undocumented

def _gen_dialect_impl(self, dialect):
def _set_parent(self, column, outer=False, **kw):
def _set_parent_with_dispatch(self, parent):
def _unwrapped_dialect_impl(self, dialect):

Return the 'unwrapped' dialect impl for this type.

This is used by the .DefaultDialect.set_input_sizes method.

__visit_name__: str =

Undocumented

_is_type_decorator: bool =
@util.memoized_property
_has_bind_expression =

memoized boolean, check if bind_expression is implemented.

Allows the method to be skipped for the vast majority of expression types that don't use this feature.

@util.memoized_property
_has_bind_processor =

memoized boolean, check if process_bind_param is implemented.

Allows the base process_bind_param to raise NotImplementedError without needing to test an expensive exception throw.

@util.memoized_property
_has_column_expression =

memoized boolean, check if column_expression is implemented.

Allows the method to be skipped for the vast majority of expression types that don't use this feature.

@util.memoized_property
_has_literal_processor =
memoized boolean, check if process_literal_param is implemented.
@util.memoized_property
_has_result_processor =

memoized boolean, check if process_result_value is implemented.

Allows the base process_result_value to raise NotImplementedError without needing to test an expensive exception throw.

@property
_type_affinity =
@property
comparator_factory =

Undocumented

@property
sort_key_function =

A sorting function that can be passed as the key to sorted.

The default value of None indicates that the values stored by this type are self-sorting.

New in version 1.3.8.