sqlalchemy-stubs
sqlalchemy-stubs copied to clipboard
Adding attribute with index_property triggers mypy warning
Hi,
I'm getting a mypy error every time I want to create a model attribute from a JSON column. My mypy config uses the sqlmypy plugin. Without using this plugin, I don't get the error.
Here is a snippet that reproduces the issue:
from sqlalchemy import Column, Integer, String
from sqlalchemy.dialects.sqlite import JSON
from sqlalchemy.ext.indexable import index_property
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Food(Base):
__tablename__ = "foods"
id = Column(Integer, primary_key=True)
name = Column(String)
properties = Column(JSON)
Food.taste = index_property("properties", "taste")
And here is the error:
demo/models.py:18:1: error: "Type[Food]" has no attribute "taste"
Found 1 error in 1 file (checked 1 source file)
Any idea how this needs to be handled? I can't add type hinting directly to the model for the taste attribute, since in my real-life use case the model doesn't know about what is contained in the properties column.
I wonder if this is because of the Food.taste = ... assignment (an attribute is defined outside a class). What if you define it within the class body as taste = index_property(...)?
If I define it inside the class, I don't get any error. This is probably how index_property is supposed to be used.
But that's not what I want to do. I want a generic Food model, with stable attributes (like name), and I want to add attributes on the fly to the class. The data contained in these attributes should be stored in database in the JSON column.
For other implementation reasons (mainly homogeneity of my APIs), I can't simply make a generic model and subclass it later.
I would understand if it's not an envisioned use case.