Reputation: 161
Is the a way to solve the issue with mypy and sqlalchemy when defining the expresison
of a hybrid property
, it triggered name <func> already defined
class User(Base):
first_name: Mapped[str] = mapped_column(String(100), nullable=False)
last_name: Mapped[str] = mapped_column(String(100), nullable=False)
@hybrid_property
def name(self) -> str:
return f"{self.first_name} {self.last_name}"
@full_name.expression
def name(cls) -> str:
return cls.first_name + " " + cls.last_name
I don't want to install external stubs package or ignore it with # type : ignore
.
Is there a way to rename the expression or something else ?
Upvotes: 0
Views: 94
Reputation: 3892
[Dez. 2024] It seems that sqlalchemy is deprecating their mypy plugin. Unfortunately, that means it is unlikely for this issue to be solvable in a neat way [by mypy].
See this Github Issue with some more cross reference.
A workaround is provided there to let the type-checker think you are using a normal property
if TYPE_CHECKING:
# This makes hybrid_property's have the same typing as normal property until stubs are improved.
hybrid_property = property
else:
from sqlalchemy.ext.hybrid import hybrid_property
Historically you can, or rather could, use SQLAlchemy's mypy plugin to help around various typing problems:
pip install sqlalchemy2-stubs
However, you should migrate away from it, please read the following advice carefully:
The SQLAlchemy Mypy Plugin is DEPRECATED, and will be removed possibly as early as the SQLAlchemy 2.1 release. We would urge users to please migrate away from it ASAP. The mypy plugin also works only up until mypy version 1.10.1. version 1.11.0 and greater may not work properly.
The mypy plugin is supported only up until mypy 1.10.1, and it will have issues running with 1.11.0 or greater. Use with mypy 1.11.0 or greater may have error conditions which currently cannot be resolved.
For SQLAlchemy 2.0, the Mypy plugin continues to work at the level at which it reached in the SQLAlchemy 1.4 release. SQLAlchemy 2.0 however features an all new typing system for ORM Declarative models that removes the need for the Mypy plugin and delivers much more consistent behavior with generally superior capabilities. Note that this new capability is not part of SQLAlchemy 1.4, it is only in SQLAlchemy 2.0.
Before that https://github.com/dropbox/sqlalchemy-stubs provided an earlier version that can be installed with pip install sqlalchemy-stubs
Upvotes: 1