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)

Commits related to this issue

Most upvoted comments

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?

from sqlalchemy import select
from sqlalchemy.orm import DeclarativeBase, Mapped, Session


class Base(DeclarativeBase):
    pass


class User(Base):
    __tablename__ = "users"

    id: Mapped[int]  # Primary key column
    name: Mapped[str]  # String column
    email: Mapped[str]  # Another string column


def get_user_by_id(session: Session, user_id: int):
    return session.scalar(select(User).where(User.id == user_id))


def search_users_by_name(session: Session, name_pattern: str):
    return session.scalars(
        select(User).where(User.name.ilike(f"%{name_pattern}%"))
    ).all()
$ ty check --python $(which python) /tmp/sqlalchemy_mapped_minimal.py
WARN ty is pre-release software and not ready for production use. Expect to encounter bugs, missing features, and fatal errors.
error[unresolved-attribute]: Attribute `id` can only be accessed on instances, not on the class object `<class 'User'>` itself.
  --> /tmp/sqlalchemy_mapped_minimal.py:18:46
   |
17 | def get_user_by_id(session: Session, user_id: int):
18 |     return session.scalar(select(User).where(User.id == user_id))
   |                                              ^^^^^^^
   |
info: rule `unresolved-attribute` is enabled by default

error[unresolved-attribute]: Attribute `name` can only be accessed on instances, not on the class object `<class 'User'>` itself.
  --> /tmp/sqlalchemy_mapped_minimal.py:28:28
   |
26 |     """
27 |     return session.scalars(
28 |         select(User).where(User.name.ilike(f"%{name_pattern}%"))
   |                            ^^^^^^^^^
29 |     ).all()
   |
info: rule `unresolved-attribute` is enabled by default

Found 2 diagnostics

What would define the category of “these descriptors”?

A __get__ overload where the instance is of type None can 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 cannot say that I really understand this code but indeed it seems like the attribute is added by a metaclass which is not detected by ty. If you think this is unrelated I can open a separate issue.

I think this is slightly different. In this case, Test has no annotation at all. The objects attribute seems to be something that is implicitly available on classes that subclass Document. So it seems to me like mongoengine could add a objects: ClassVar[list[object]] annotation to TopLevelDocumentMetaclass to make this explicit: https://play.ty.dev/224a3bdc-54c1-4fbf-8991-723aa526c002.

Thank you for reporting this.

I have trouble reproducing this:

> uv init
> uv add sqlalchemy
> uvx ty check
WARN ty is pre-release software and not ready for production use. Expect to encounter bugs, missing features, and fatal errors.
All checks passed!

Can you please add more details how you ran ty and 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 the mapped_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)