Skip to content

MappedAsDataclass Optional generates non-Optional typing annotations #9855

Closed as not planned
@BranislavBajuzik

Description

@BranislavBajuzik

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 having MappedAsDataclass in the class hierarchy, Mypy reports Optional attributes as not Optional.

The generated DDL is correct, without the NOT NULL part

To Reproduce

from sqlalchemy.orm import MappedAsDataclass, DeclarativeBase, Mapped


class Test(MappedAsDataclass, DeclarativeBase):
    __tablename__ = "test"
    test_str_attribute: Mapped[str | None]


Test(test_str_attribute=None)

Error

error: Argument "test_str_attribute" to "Test" has incompatible type "None"; expected "Union[SQLCoreOperations[Optional[str]], str]"  [arg-type]

Versions

  • OS: Kubuntu 22.04
  • Python: 3.10.6
  • SQLAlchemy: 2.0.15
  • Type checker: mypy 1.3.0 (compiled: yes)

Additional context

This seems oddly similar to #9567, but the referenced mypy issue, python/mypy#13856, is marked as resolved in 1.2 (also in docs)

Thank you

Metadata

Metadata

Assignees

No one assigned

    Labels

    dataclassesduplicateThis issue or pull request already existsormthird 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