DanCardin / sqlalchemy-declarative-extensions

Library to declare additional kinds of objects not natively supported by SqlAlchemy/Alembic.
https://sqlalchemy-declarative-extensions.readthedocs.io/en/latest/
Apache License 2.0
31 stars 5 forks source link

mypy issues with DeclarativeBase #37

Closed YaraslauZhylko closed 1 year ago

YaraslauZhylko commented 1 year ago

sqlalchemy-declarative-extensions documentation suggests to declare the ORM base class like this:

from sqlalchemy_declarative_extensions.sqlalchemy import declarative_base
from sqlalchemy_declarative_extensions import declarative_database

_Base = declarative_base()

@declarative_database
class Base(_Base):
    __abstract__ = True

But as of now, declarative_base is being deprecated:

Changed in version 2.0: Note that the declarative_base() function is superseded by the new DeclarativeBase class, which generates a new “base” class using subclassing, rather than return value of a function. This allows an approach that is compatible with PEP 484 typing tools.

So I try to use DeclarativeBase as a base class like this:

from sqlalchemy.orm import DeclarativeBase
from sqlalchemy_declarative_extensions import declarative_database

@declarative_database
class Base(DeclarativeBase):
    __abstract__ = True

And as a result, I get a mypy error:

error: Value of type variable "T" of "declarative_database" cannot be "type[Base]" [type-var]

I guess the following line needs some adjustment to get work with both the old and the new declaration style: https://github.com/DanCardin/sqlalchemy-declarative-extensions/blob/bd52ff8bd90220c97a3a20b62dba4d37857b1dfb/src/sqlalchemy_declarative_extensions/api.py#L24

DanCardin commented 1 year ago

Thanks for the report! I'm not sure how much utility that bound is providing anyways. I have a solution, but it no longer actually references sqlalchemy types.

Before I release it, I wonder if you might install this branch https://github.com/DanCardin/sqlalchemy-declarative-extensions/pull/38 and see if it fixes your issue?

I dont have any real sqlalchemy2 projects handy, and I'm not entirely convinced this wont have side effects.

DanCardin commented 1 year ago

I've reverted to runtime checks here, because it seems to be impossible/impractical to have actually typed input types that support both versions.

As a result, I suspect it's much more likely to "just work" so I just merged/released it in v0.6.4.

Lmk if this does/doesnt solve your problem!

YaraslauZhylko commented 1 year ago

I'm sorry I missed the GitHub notification.

I tried the 0.6.4 release and it seems to have fixed the issue. At least I do not need # type: ignore any more. 😅

No regressions encountered so far.

Thank you.