I am using sqlite3 for db access in a python module.
I frequently use enums in my python objects. Currently I have to convert my enums into strings before inserting them into the sqlite db. My following attempt to register a generic adapter to make this conversion implicit fails.
def adapt_enum(enum_instance):
return enum_instance.name
sqlite3.register_adapter(enum.Enum,adapt_enum)
The above implementation results in the following error.
sqlite3.InterfaceError: Error binding parameter 5 - probably unsupported type.
Registering an adapter for each enum, as shown below works fine however
class MyEnum(Enum):
a = 1
b = 2
def adapt_my_enum(my_enum_instance):
return my_enum_instance.name
sqlite3.register_adapter(MyEnum,adapt_my_enum)
The adapter for MyEnum works as expected. But going this way I have to register an adapter for all my enums separately. Is there a way to remove this redundancy?
P.S. I am using python 2.7
Looks like the easier way is to build the adaptation into the Enum itself:
class SqliteEnum(enum.Enum):
def __conform__(self, protocol):
if protocol is sqlite3.PrepareProtocol:
return self.name
and then use SqliteEnum as the base for your other Enum classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With