Skip to content

Cannot define declarative base class as attribute of object #54

Open
@MaicoTimmerman

Description

@MaicoTimmerman

Describe the bug
I'd like to switch from the dropbox/sqlalchemy stubs to the official stubs, however when the declarative base is defined as attribute of an instance, it is not recognized as valid base class.

The Dropbox stubs give similar errors regarding the subclassing, however the types are still correctly inferred.

Expected behavior
Type definitions to be picked up as the builtin types: test.py:20: note: Revealed type is 'Union[builtins.int, None]'

To Reproduce

from sqlalchemy.schema import Column
from sqlalchemy.types import Integer, String
from sqlalchemy.orm.decl_api import DeclarativeMeta, declarative_base

db = DB()

class DB():
    def __init__(self):
        self.Base = declarative_base()


class A(db.Base):
    __tablename__ = "a"
    id = Column(Integer, primary_key=True)

a = A()
reveal_type(a.id)

Error

test2.py:12: error: Name 'db.Base' is not defined
test2.py:17: note: Revealed type is 'sqlalchemy.sql.schema.Column[sqlalchemy.sql.sqltypes.Integer*]'
Found 1 error in 1 file (checked 1 source file)

Versions.

  • OS: Arch linux
  • Python: 3.9
  • SQLAlchemy: 1.4.5 + mypy plugin
  • Database: n/a
  • DBAPI: n/a

Additional context
The problem seems similar to one described on StackOverflow. However, I expected that replacing the direct subclassing with a typed variable would resort the problem.

Example code
from sqlalchemy.schema import Column
from sqlalchemy.types import Integer, String
from sqlalchemy.orm.decl_api import DeclarativeMeta, declarative_base

db = DB()

class DB():
    def __init__(self):
        self.Base = declarative_base()

Base: DeclarativeMeta = db.Base

class A(Base):
    __tablename__ = "a"
    id = Column(Integer, primary_key=True)

a = A()
reveal_type(a.id)

Have a nice day!

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions