Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Mapped property is interpreted to mapped type instead of InstrumentedAttibute on union #10751

@Fred-si

Description

@Fred-si

Ensure stubs packages are not installed

  • No sqlalchemy stub packages is installed (both sqlalchemy-stubs and sqlalchemy2-stubs are not compatible with v2)

Verify if the api is typed

  • The api is not in a module listed in #6810 so it should pass type checking

Describe the typing issue

When I have a variable that contain an union of model type (foo: type[ModelA | ModelB]) property type is interpreted by mypy as mapped_type instead of InstrumentedAttribute[mapped_type].

To Reproduce

from typing_extensions import reveal_type

from sqlalchemy.orm import DeclarativeBase, Mapped


class Foo(DeclarativeBase):
    foobar: Mapped[str]


class Bar(DeclarativeBase):
    foobar: Mapped[str]


def foo(attribute: InstrumentedAttribute[Any]) -> None:
    pass


union: type[Foo | Bar] = Foo
foo(union.foobar)

Error

main.py:21: error: Argument 1 to "foo" has incompatible type "str"; expected "InstrumentedAttribute[Any]"  [arg-type]

Versions

  • OS: Ubuntu 20.04
  • Python: 3.10.12 | 3.11.6 | 3.12.0
  • SQLAlchemy: 2.0.22 | 2.0.23
  • Type checker (eg: mypy 0.991, pyright 1.1.290, etc): mypy 1.7.1

Additional context

sqlalchemy and mypy are installed in venv

requirements.txt

SQLAlchemy==2.0.23
mypy==1.7.1

minimal example can be found here https://github.com/Fred-si/sqlalchemy_union_type_issue

Metadata

Metadata

Assignees

No one assigned

    Labels

    third party integration issuesissues to do with other libraries and frameworkstypingpep -484 typing issues. independent of "mypy"

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions