class documentation

class Enum(Emulated, String, SchemaType):

Known subclasses: sqlalchemy.dialects.mysql.enumerated.ENUM, sqlalchemy.dialects.postgresql.ENUM, sqlalchemy.dialects.oracle.cx_oracle._OracleEnum

View In Hierarchy

Generic Enum Type.

The .Enum type provides a set of possible string values which the column is constrained towards.

The .Enum type will make use of the backend's native "ENUM" type if one is available; otherwise, it uses a VARCHAR datatype. An option also exists to automatically produce a CHECK constraint when the VARCHAR (so called "non-native") variant is produced; see the :paramref:`.Enum.create_constraint` flag.

The .Enum type also provides in-Python validation of string values during both read and write operations. When reading a value from the database in a result set, the string value is always checked against the list of possible values and a LookupError is raised if no match is found. When passing a value to the database as a plain string within a SQL statement, if the :paramref:`.Enum.validate_strings` parameter is set to True, a LookupError is raised for any string value that's not located in the given list of possible values; note that this impacts usage of LIKE expressions with enumerated values (an unusual use case).

Changed in version 1.1: the .Enum type now provides in-Python validation of input values as well as on data being returned by the database.

The source of enumerated values may be a list of string values, or alternatively a PEP-435-compliant enumerated class. For the purposes of the .Enum datatype, this class need only provide a __members__ method.

When using an enumerated class, the enumerated objects are used both for input and output, rather than strings as is the case with a plain-string enumerated type:

import enum
class MyEnum(enum.Enum):
    one = 1
    two = 2
    three = 3

t = Table(
    'data', MetaData(),
    Column('value', Enum(MyEnum))
)

connection.execute(t.insert(), {"value": MyEnum.two})
assert connection.scalar(t.select()) is MyEnum.two

Above, the string names of each element, e.g. "one", "two", "three", are persisted to the database; the values of the Python Enum, here indicated as integers, are not used; the value of each enum can therefore be any kind of Python object whether or not it is persistable.

In order to persist the values and not the names, the :paramref:`.Enum.values_callable` parameter may be used. The value of this parameter is a user-supplied callable, which is intended to be used with a PEP-435-compliant enumerated class and returns a list of string values to be persisted. For a simple enumeration that uses string values, a callable such as lambda x: [e.value for e in x] is sufficient.

New in version 1.1: - support for PEP-435-style enumerated classes.

See Also

_postgresql.ENUM - PostgreSQL-specific type, which has additional functionality.

.mysql.ENUM - MySQL-specific type

Method __init__ Construct an enum.
Class ​Comparator Undocumented
Method __repr__ Undocumented
Method ​_db​_value​_for​_elem Undocumented
Method ​_enum​_init internal init for .Enum and subclasses.
Method ​_object​_value​_for​_elem Undocumented
Method ​_parse​_into​_values Undocumented
Method ​_set​_table Undocumented
Method ​_setup​_for​_values Undocumented
Method ​_should​_create​_constraint Undocumented
Method adapt Produce an "adapted" form of this type, given an "impl" class to work with.
Method adapt​_to​_emulated Given an impl class, adapt this type to the impl assuming "emulated".
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 bind​_processor Return a conversion function for processing bind values.
Method copy Undocumented
Method literal​_processor Return a conversion function for processing literal values that are to be rendered directly without using binds.
Method result​_processor Return a conversion function for processing result row values.
Class Variable __visit​_name__ Undocumented
Instance Variable ​_object​_lookup Undocumented
Instance Variable ​_omit​_aliases Undocumented
Instance Variable ​_sort​_key​_function Undocumented
Instance Variable ​_valid​_lookup Undocumented
Instance Variable create​_constraint Undocumented
Instance Variable enum​_class Undocumented
Instance Variable enums Undocumented
Instance Variable native​_enum Undocumented
Instance Variable validate​_strings Undocumented
Instance Variable values​_callable Undocumented
Property ​_enums​_argument Undocumented
Property native Undocumented
Property python​_type Return the Python type object expected to be returned by instances of this type, if known.
Property sort​_key​_function A sorting function that can be passed as the key to sorted.

Inherited from String:

Method get​_dbapi​_type Return the corresponding type object from the underlying DB-API, if any.
Constant RETURNS​_BYTES Undocumented
Constant RETURNS​_CONDITIONAL Undocumented
Constant RETURNS​_UNICODE Undocumented
Constant RETURNS​_UNKNOWN Undocumented
Class Method ​_warn​_deprecated​_unicode Undocumented
Instance Variable ​_expect​_unicode Undocumented
Instance Variable ​_expect​_unicode​_error Undocumented
Instance Variable ​_warn​_on​_bytestring Undocumented
Instance Variable collation Undocumented
Instance Variable length Undocumented

Inherited from TypeEngine (via String):

Method bind​_expression Given a bind value (i.e. a .BindParameter instance), return a SQL expression in its place.
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​_against​_backend Compare this type against the given backend type.
Method compare​_values Compare two values for equality.
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 ​_gen​_dialect​_impl Undocumented
Method ​_resolve​_for​_literal adjust this type given a literal Python value that will be stored in a bound parameter.
Method ​_unwrapped​_dialect​_impl Return the 'unwrapped' dialect impl for this type.
Method copy​_value Undocumented
Class Variable ​_is​_array Undocumented
Class Variable ​_is​_table​_value Undocumented
Class Variable ​_is​_tuple​_type Undocumented
Class Variable ​_is​_type​_decorator Undocumented
Class Variable ​_isnull Undocumented
Class Variable ​_sqla​_type Undocumented
Property ​_generic​_type​_affinity Undocumented
Property ​_has​_bind​_expression memoized boolean, check if bind_expression is implemented.
Property ​_has​_column​_expression memoized boolean, check if column_expression is implemented.
Property ​_static​_cache​_key Undocumented
Property ​_type​_affinity Return a rudimental 'affinity' value expressing the general class of type.

Inherited from Traversible (via String, TypeEngine):

Method get​_children Return immediate child .visitors.Traversible elements of this .visitors.Traversible.
Method __class​_getitem__ Undocumented

Inherited from SchemaType:

Method ​_is​_impl​_for​_variant Undocumented
Method ​_on​_metadata​_create Undocumented
Method ​_on​_metadata​_drop Undocumented
Method ​_on​_table​_create Undocumented
Method ​_on​_table​_drop Undocumented
Method ​_set​_parent Associate with this SchemaEvent's parent object.
Method ​_variant​_mapping​_for​_set​_table Undocumented
Method create Issue CREATE DDL for this type, if applicable.
Method drop Issue DROP DDL for this type, if applicable.
Class Variable ​_use​_schema​_map Undocumented
Instance Variable ​_create​_events Undocumented
Instance Variable inherit​_schema Undocumented
Instance Variable metadata Undocumented
Instance Variable name Undocumented
Instance Variable schema Undocumented
Property bind Undocumented

Inherited from SchemaEventTarget (via SchemaType):

Method ​_set​_parent​_with​_dispatch Undocumented
@util.deprecated_params(convert_unicode=('1.3', 'The :paramref:`.Enum.convert_unicode` parameter is deprecated and will be removed in a future release. All modern DBAPIs now support Python Unicode directly and this parameter is unnecessary.'))
def __init__(self, *enums, **kw):

Construct an enum.

Keyword arguments which don't apply to a specific backend are ignored by that backend.

Parameters
*enums

either exactly one PEP-435 compliant enumerated type or one or more string labels.

New in version 1.1: a PEP-435 style enumerated class may be passed.
**kwUndocumented
convert​_unicodeEnable unicode-aware bind parameter and result-set processing for this Enum's data under Python 2 only. Under Python 2, this is set automatically based on the presence of unicode label strings. This flag will be removed in SQLAlchemy 2.0.
create​_constraint

defaults to False. When creating a non-native enumerated type, also build a CHECK constraint on the database against the valid values.

Note

it is strongly recommended that the CHECK constraint have an explicit name in order to support schema-management concerns. This can be established either by setting the :paramref:`.Enum.name` parameter or by setting up an appropriate naming convention; see :ref:`constraint_naming_conventions` for background.

Changed in version 1.4: - this flag now defaults to False, meaning no CHECK constraint is generated for a non-native enumerated type.
metadata

Associate this type directly with a MetaData object. For types that exist on the target database as an independent schema construct (PostgreSQL), this type will be created and dropped within create_all() and drop_all() operations. If the type is not associated with any MetaData object, it will associate itself with each Table in which it is used, and will be created when any of those individual tables are created, after a check is performed for its existence. The type is only dropped when drop_all() is called for that Table object's metadata, however.

The value of the :paramref:`_schema.MetaData.schema` parameter of the _schema.MetaData object, if set, will be used as the default value of the :paramref:`_types.Enum.schema` on this object if an explicit value is not otherwise supplied.

Changed in version 1.4.12: _types.Enum inherits the :paramref:`_schema.MetaData.schema` parameter of the _schema.MetaData object if present, when passed using the :paramref:`_types.Enum.metadata` parameter.
nameThe name of this type. This is required for PostgreSQL and any future supported database which requires an explicitly named type, or an explicitly named constraint in order to generate the type and/or a table that uses it. If a PEP-435 enumerated class was used, its name (converted to lower case) is used by default.
native​_enumUse the database's native ENUM type when available. Defaults to True. When False, uses VARCHAR + check constraint for all backends. The VARCHAR length can be controlled with :paramref:`.Enum.length`
length

Allows specifying a custom length for the VARCHAR when :paramref:`.Enum.native_enum` is False. By default it uses the length of the longest value.

New in version 1.3.16.
schema

Schema name of this type. For types that exist on the target database as an independent schema construct (PostgreSQL), this parameter specifies the named schema in which the type is present.

If not present, the schema name will be taken from the _schema.MetaData collection if passed as :paramref:`_types.Enum.metadata`, for a _schema.MetaData that includes the :paramref:`_schema.MetaData.schema` parameter.

Changed in version 1.4.12: _types.Enum inherits the :paramref:`_schema.MetaData.schema` parameter of the _schema.MetaData object if present, when passed using the :paramref:`_types.Enum.metadata` parameter.

Otherwise, if the :paramref:`_types.Enum.inherit_schema` flag is set to True, the schema will be inherited from the associated _schema.Table object if any; when :paramref:`_types.Enum.inherit_schema` is at its default of False, the owning table's schema is not used.

quoteSet explicit quoting preferences for the type's name.
inherit​_schemaWhen True, the "schema" from the owning _schema.Table will be copied to the "schema" attribute of this .Enum, replacing whatever value was passed for the schema attribute. This also takes effect when using the _schema.Table.to_metadata operation.
validate​_strings

when True, string values that are being passed to the database in a SQL statement will be checked for validity against the list of enumerated values. Unrecognized values will result in a LookupError being raised.

New in version 1.1.0b2.
values​_callable

A callable which will be passed the PEP-435 compliant enumerated type, which should then return a list of string values to be persisted. This allows for alternate usages such as using the string value of an enum to be persisted to the database instead of its name.

New in version 1.2.3.
sort​_key​_function

a Python callable which may be used as the "key" argument in the Python sorted() built-in. The SQLAlchemy ORM requires that primary key columns which are mapped must be sortable in some way. When using an unsortable enumeration object such as a Python 3 Enum object, this parameter may be used to set a default sort key function for the objects. By default, the database value of the enumeration is used as the sorting function.

New in version 1.3.8.
omit​_aliases

A boolean that when true will remove aliases from pep 435 enums. For backward compatibility it defaults to False. A deprecation warning is raised if the enum has aliases and this flag was not set.

New in version 1.4.5.
Deprecated since version 1.4: The default will be changed to True in SQLAlchemy 2.0.
def __repr__(self):
def _db_value_for_elem(self, elem):

Undocumented

def _enum_init(self, enums, kw):

internal init for .Enum and subclasses.

friendly init helper used by subclasses to remove all the Enum-specific keyword arguments from kw. Allows all other arguments in kw to pass through.

def _object_value_for_elem(self, elem):

Undocumented

def _parse_into_values(self, enums, kw):

Undocumented

@util.preload_module('sqlalchemy.sql.schema')
def _set_table(self, column, table):
def _setup_for_values(self, values, objects, kw):

Undocumented

def _should_create_constraint(self, compiler, **kw):

Undocumented

def adapt(self, impltype, **kw):

Produce an "adapted" form of this type, given an "impl" class to work with.

This method is used internally to associate generic types with "implementation" types that are specific to a particular dialect.

def adapt_to_emulated(self, impltype, **kw):

Given an impl class, adapt this type to the impl assuming "emulated".

The impl should also be an "emulated" version of this type, most likely the same class as this type itself.

e.g.: sqltypes.Enum adapts to the Enum class.

def as_generic(self, allow_nulltype=False):

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.

>>> from sqlalchemy.dialects.mysql import INTEGER
>>> INTEGER(display_width=4).as_generic()
Integer()
>>> from sqlalchemy.dialects.mysql import NVARCHAR
>>> NVARCHAR(length=100).as_generic()
Unicode(length=100)
New in version 1.4.0b2.

See Also

:ref:`metadata_reflection_dbagnostic_types` - describes the use of _types.TypeEngine.as_generic in conjunction with the _sql.DDLEvents.column_reflect event, which is its intended use.

def bind_processor(self, dialect):

Return a conversion function for processing bind values.

Returns a callable which will receive a bind parameter value as the sole positional argument and will return a value to send to the DB-API.

If processing is not necessary, the method should return None.

Note

This method is only called relative to a dialect specific type object, which is often private to a dialect in use and is not the same type object as the public facing one, which means it's not feasible to subclass a .types.TypeEngine class in order to provide an alternate _types.TypeEngine.bind_processor method, unless subclassing the _types.UserDefinedType class explicitly.

To provide alternate behavior for _types.TypeEngine.bind_processor, implement a _types.TypeDecorator class and provide an implementation of _types.TypeDecorator.process_bind_param.

Parameters
dialectDialect instance in use.
def copy(self, **kw):

Undocumented

def literal_processor(self, dialect):

Return a conversion function for processing literal values that are to be rendered directly without using binds.

This function is used when the compiler makes use of the "literal_binds" flag, typically used in DDL generation as well as in certain scenarios where backends don't accept bound parameters.

Returns a callable which will receive a literal Python value as the sole positional argument and will return a string representation to be rendered in a SQL statement.

Note

This method is only called relative to a dialect specific type object, which is often private to a dialect in use and is not the same type object as the public facing one, which means it's not feasible to subclass a .types.TypeEngine class in order to provide an alternate _types.TypeEngine.literal_processor method, unless subclassing the _types.UserDefinedType class explicitly.

To provide alternate behavior for _types.TypeEngine.literal_processor, implement a _types.TypeDecorator class and provide an implementation of _types.TypeDecorator.process_literal_param.

def result_processor(self, dialect, coltype):

Return a conversion function for processing result row values.

Returns a callable which will receive a result row column value as the sole positional argument and will return a value to return to the user.

If processing is not necessary, the method should return None.

Note

This method is only called relative to a dialect specific type object, which is often private to a dialect in use and is not the same type object as the public facing one, which means it's not feasible to subclass a .types.TypeEngine class in order to provide an alternate _types.TypeEngine.result_processor method, unless subclassing the _types.UserDefinedType class explicitly.

To provide alternate behavior for _types.TypeEngine.result_processor, implement a _types.TypeDecorator class and provide an implementation of _types.TypeDecorator.process_result_value.

Parameters
dialectDialect instance in use.
coltypeDBAPI coltype argument received in cursor.description.
__visit_name__: str =
_object_lookup =

Undocumented

_omit_aliases =

Undocumented

_sort_key_function =

Undocumented

_valid_lookup =

Undocumented

create_constraint =

Undocumented

enum_class =

Undocumented

enums =

Undocumented

validate_strings =

Undocumented

values_callable =

Undocumented

@property
_enums_argument =

Undocumented

@property
native =

Undocumented

@property
python_type =

Return the Python type object expected to be returned by instances of this type, if known.

Basically, for those types which enforce a return type, or are known across the board to do such for all common DBAPIs (like int for example), will return that type.

If a return type is not defined, raises NotImplementedError.

Note that any type also accommodates NULL in SQL which means you can also get back None from any type in practice.

@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.