db independent Enum column type

Issue #246 resolved
Former user created an issue

An Enum type. Is basically a Unicode type but restricts the values that you can set in the column to specific list of values.

class Enum(types.Unicode):

    def __init__(self, values, empty_to_none=False):      
        **
        contruct an Enum type

        values : a list of values that are valid for this column
        empty_to_none : treat the empty string '' as None
        **
        if values is None or len(values) is 0:
            raise exceptions.AssertionError('Enum requires a list of values')
        self.empty_to_none = empty_to_none
        self.values = values
        # the length of the string/unicode column should be the longest string
        # in values
        super(Enum, self).__init__(len(max(values)))


    def convert_bind_param(self, value, engine):
        if self.empty_to_none and value is '':
            value = None
        if value not in self.values:
            raise exceptions.AssertionError('%s not in Enum.values' % value)
        return super(Enum, self).convert_bind_param(value, engine)


    def convert_result_value(self, value, engine):
        if value not in self.values:
            raise exceptions.AssertionError('%s not in Enum.values' % value)
        return super(Enum, self).convert_result_param(value, engine)

Comments (1)

  1. Mike Bayer repo owner

    id rather keep this as a wiki recipe for now...its ambiguous if we'd want the MySQL version of "enum" to actually create a real "enum" or not, also i dont see the "empty_to_none" argument as particularly useful (we have None when we want None), so i see a little too many assumptions to make for a core type.

  2. Log in to comment