Using `Relationship[]` as annotation of a relationship set up a dynamic relationship instead of a normal one
Exmaple:
import sqlalchemy as sa
from sqlalchemy import orm
class B(orm.DeclarativeBase):
pass
class M(B):
__tablename__ = "foo"
id: orm.Mapped[int] = orm.mapped_column(primary_key=True)
xid: orm.Mapped[int] = orm.mapped_column(sa.ForeignKey("x.id"))
class X(B):
__tablename__ = "x"
id: orm.Mapped[int] = orm.mapped_column(primary_key=True)
ms_map: orm.Mapped[list[M]] = orm.relationship(viewonly=True)
ms_rel: orm.Relationship[list[M]] = orm.relationship(viewonly=True)
orm.configure_mappers()
print(type(X.ms_map.impl))
print(type(X.ms_rel.impl))
the following prints
<class 'sqlalchemy.orm.attributes.CollectionAttributeImpl'>
<class 'sqlalchemy.orm.dynamic.DynamicAttributeImpl'>
The two cases should result in the same behaviour
So the situation does not make sense if we try to stick to typing, as opposed to a hardcoded rule to check for Relationship. Short answer is people should not use Relationship in this way. Basically I will just replace it with a private class that extends Relationship, allowing this case to work. but that means nobody would even know Relationship exists anymore.
so we circle around. How does one know that Relationship is a class and is viable here? seen in the rollover?
Mike Bayer has proposed a fix for this issue in the main branch:
use a private return class for the "catch all" relationship https://gerrit.sqlalchemy.org/c/sqlalchemy/sqlalchemy/+/4946
so check out the "fix". it's that, or we add some hardcoded rule to look for "Relationship" at runtime and we are not really doing typing correctly.
so we circle around. How does one know that Relationship is a class and is viable here? seen in the rollover?
well it's exported from the orm.__init__ so people may just do orm.Rel the editor autocompletes with Relationship. That's how I found this
As an end user, I would prefer to only see Mapped work for typing like this - or at least documented. The reason is for simplified audits and code reviews.
As an end user, I would prefer to only see
Mappedwork for typing like this - or at least documented. The reason is for simplified audits and code reviews.
yes, same here, but at the very least this case should not do something surprising like setting the dynamic relationship type
yes, same here, but at the very least this case should not do something surprising like setting the dynamic relationship type
Apologies. I erroneously read the above as reveal_type( and not type(. Yes, that is problematic.
Mike Bayer has proposed a fix for this issue in the rel_2_0 branch:
use a private return class for the "catch all" relationship https://gerrit.sqlalchemy.org/c/sqlalchemy/sqlalchemy/+/5236