Monday, 9 August 2021

How to resolve mypy error with sqlalchemy enum?

mypy reports an error in the following code:

import enum
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Enum

Base = declarative_base()

class MyEnum(enum.Enum):
    A = 1
    B = 2

class MyTable(Base):
    __tablename__ = 'my_table'

    col = Column(Enum(MyEnum), nullable=False)

c = MyTable(col=MyEnum.A)

Following is the error:

a.py:16: error: Incompatible type for "col" of "MyTable" (got "MyEnum", expected "str")

How do I make this error go away without adding a "type: ignore" ? I could also replace MyEnum.A with MyEnum.A.name to make the error go away. But this doesn't look clean and is also not suggested in sqlalchemy documentation.



from How to resolve mypy error with sqlalchemy enum?

No comments:

Post a Comment