ty: Declared-only attributes are not accessible on instances of the class
Summary
When using SQLAlchemy’s declarative models with Mapped type annotations, ty incorrectly reports that model class attributes (which represent database columns) can only be accessed on instances, not on the class itself.
Example
from uuid import UUID
from sqlalchemy import select
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session
class Base(DeclarativeBase):
pass
class Organization(Base):
__tablename__ = "organizations"
id: Mapped[int] = mapped_column(primary_key=True)
uuid: Mapped[UUID] = mapped_column(unique=True)
name: Mapped[str] = mapped_column()
def get_organization(session: Session, org_uuid: UUID):
# ty incorrectly reports: "Attribute `uuid` can only be accessed on instances"
return session.scalar(
select(Organization).where(Organization.uuid == org_uuid)
)
See SQLAlchemy’s documentation on querying for more examples.
Version
ty 0.0.1-alpha.1
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Reactions: 11
- Comments: 17 (11 by maintainers)
After seeing another non-SQLAlchemy case of this in https://github.com/astral-sh/ty/issues/553, I’m leaning towards just abandoning our current strict handling of annotated-but-not-assigned names in class bodies, and just allow them to be considered a class-or-instance attribute, as mypy and pyright do. I still think it would have been better for the type system to go a different direction here, but I don’t want to take on the burden of incompatibility with too much existing typed code.
@sharkdp sorry about that! I made a mistake when trying to create a minimal repro 😄 - does this work better?
A
__get__overload where the instance is of typeNonecan only logically apply to the class. It’s not clean, but it might be better than carving out an exception for SQLAlchemy specifically?Thank you for explaining ty’s approach to class variables.
I think this is slightly different. In this case,
Testhas no annotation at all. Theobjectsattribute seems to be something that is implicitly available on classes that subclassDocument. So it seems to me like mongoengine could add aobjects: ClassVar[list[object]]annotation toTopLevelDocumentMetaclassto make this explicit: https://play.ty.dev/224a3bdc-54c1-4fbf-8991-723aa526c002.Thank you for reporting this.
I have trouble reproducing this:
Can you please add more details how you ran
tyand what the environment looks like?I can see how we would show that message if there was no right hand side in the attribute assignment (
uuid: Mapped[UUID]), but with themapped_column(…)right-hand-side, we should understand that this can also be accessed on the class itself.That said, we don’t fully support dataclass fields yet, so I wouldn’t expect support for sqlalchemy models to be complete (see #111)