-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
typing.Self not supported in generic fields #9391
Comments
Yep, you're right, this isn't currently supported. I've marked this as a feature request. PRs with support are welcome! |
@sydney-runkle Hey, I started looking into this, and it seems a little tricky to me. In the definition of class Entity(BaseModel):
ref: Ref[Self]
My best idea was to perhaps look try to look up the stack to figure out what Do you perhaps have any ideas/directions into how this should be implemented? |
@NeevCohen I don't believe it's a trial patch to handle the generic case. The code example above it's too hard (you use the new cls instance being constructed in the pydantic base model meta-class but e.g. what happens when Product has a subclass or what happens when there's an intermediate abstract class in the MRO / class hierarchy chain. There's also the issue that For this simple case, you can change class Entity(BaseModel):
ref: "Ref[Self]"
@classmethod
@override
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
# Specialize the ref field type to the concrete Entity subclass.
# This works around https://github.com/pydantic/pydantic/issues/9391
# This patching of field-info must happen in __init_subclass__ (before
# __pydantic_init_subclass__) so the correct core schema is generated for the model.
ref_fi = cls.model_fields["ref"]
# if ref_fi.annotation == Union[Ref[Self], None]:
# but only if the type is not yet specialized so we can handle model lineages in a
# slightly hacky way by setting the ref type to be the same across all versions.
ref_fi.annotation = Union[Ref[cls], None] # noqa: UP007 # we actually need to create a UnionType instance here.
cls.model_fields["ref"] = ref_fi @NeevCohen you could also look at |
Initial Checks
Description
It seems that with the recent introduction to support the
Self
type in pydantic 2.7 #5992, this doesn't cover support for generic fields whereSelf
is the type var.Alternatives:
Product
has the following field info.At the point of model creation, I believe it should be possible to update
Ref[Self]
toRef[model_class]
? The downside here is that the FieldInfo, while it reflects the reality of the semantics of the Self type, no longer matches the annotation verbatim making it harder to potentially debug, easier to introduce bugs (e.g. if the annotation value is used to look up the cached generic subclass) ad potentially incompatible with whatever direction the python core team takes__future__ annotations
in.Example Code
The text was updated successfully, but these errors were encountered: