Reputation: 151
Using the latest querying patterns from SQLAlchemy 2.0 (https://docs.sqlalchemy.org/en/20/tutorial/data_select.html) and want to annotate my CRUD functions. I am using Python 3.11 and Mypy 1.4.0.
There is some documentation on how to do typing but it's not working for me.
There is something in these docs about how all stubs must be uninstalled for typing to work but I don't seem to have any stubs installed.
Here's an example of what I have:
if TYPE_CHECKING:
from sqlalchemy.orm import Session
from sqlalchemy import Row, Sequence, Tuple
from app.models import User as UserDBModel
UserRow = Row[Tuple[UserDBModel]]
def get_users(db: Session, skip: int = 0, limit: int = 100) -> Sequence[UserRow]:
return db.scalars(select(UserDBModel).offset(skip).limit(limit)).all()
For UserRow
Mypy complains as follows: Type argument "sqlalchemy.sql.elements.Tuple" of "Row" must be a subtype of "tuple[Any, ...]" [type-var]mypy(error) Value of type variable "_TP" of "Row" cannot be "sqlalchemy.sql.elements.Tuple" [type-var]mypy(error)
But doing what it says doesn't work.
For the function return type, Mypy says the following: Incompatible return value type (got "typing.Sequence[Row[tuple[User]]]", expected "sqlalchemy.sql.schema.Sequence") [return-value]
. But if I replace the Sequence import with the one from that path, it makes the same complaint!
Am I doing something wrong? If I am not doing something wrong, has anyone got around these kind of errors? Or is the problem upstream of me and I should give up on explicit annotations for now?
Upvotes: 1
Views: 1784
Reputation: 151
Ok turns out the correct annotation when using the above syntax is just Sequence[User]
as https://stackoverflow.com/users/5320906/snakecharmerb pointed out. I had misunderstood the docs when I first read them
Upvotes: 0