[Python] Static type for "any SQLAlchemy ORM class with an integer field named 'id'"

Discussão em 'Python' iniciado por Stack, Agosto 17, 2025.

  1. Stack

    Stack Membro Participativo

    How can I give a static type to a function that should accept "any SQLAlchemy ORM class with an integer field named 'id'"?

    Below are my attempts, commented with the mypy errors I got. I had to resort to id: Any but I still hope I can do better.

    I can't modify the ORM classes, so I can't to add an intermediate class BaseWithId between Base and Foo.

    I'm open to solutions, workarounds, or explanations why it's impossible.

    from typing import Any, Protocol, TypeVar
    import sqlalchemy as sql
    from sqlalchemy import orm


    class HasIntId(Protocol):
    # id: int # Argument 1 to "where" of "Select" has incompatible type "bool" ... [arg-type]
    # id: orm.Mapped[int] # Value of type variable "T" of "f" cannot be "Foo" [type-var]
    # id: orm.attributes.InstrumentedAttribute[int] # Value of type variable "T" of "f" cannot be "Foo" [type-var]
    id: Any

    T = TypeVar('T', bound=HasIntId)

    def f(model: type[T]) -> sql.Select[tuple[T]]:
    return sql.select(model).where(model.id > 42).order_by(model.id.desc())


    class Base(orm.DeclarativeBase):
    pass

    class Foo(Base):
    __tablename__ = 'foos'
    id: orm.Mapped[int] = orm.mapped_column(primary_key=True)


    print(f(Foo))

    Continue reading...

Compartilhe esta Página