Replies: 1 comment 1 reply
-
I kind of understand what you're trying to do here, but the relationships between your various classes is really contorted. You are effectively trying to override the constructor for an If you want to stick to your current formulation, here are some thoughts... When you assign the value of a class or instance variable without providing a type declaration, pyright assumes that you want to use the type declaration from the base class. In your case, class SubItem(Item):
builder: ClassVar["Builder[SubItem]"] = Builder["SubItem"](5) Another approach is to make the class Item(BaseModel):
value: int
builder: ClassVar[Builder[Any]] = default_builder
@classmethod
def build(cls: Type[_I]) -> _I:
return cls.builder.build(cls) |
Beta Was this translation helpful? Give feedback.
-
I want to do some seemingly simple typing but have hard time expressing it in Python.
Say I have this data class:
Now say I have a builder for any subtype of
Item
:And here's the typing problem I've faced so far.
I want to define a builder as a class variable for the item itself that will be built:
reveal_type(Item.builder)
correctly identifies that the type isBuilder[Item]
.But if I have other items inheriting from
Item
:The inferred type is still
Builder["Item"]
.Is there a way to express that the generic type variable is always the type of the class containing the
builder
?Then ideally this would make
pyright
infer the type for subitems:Since me and my colleague didn't find any ways to express this we did a bunch of experiments with metaclasses hoping to hint
pyright
about the constructed class (i.e. subtypes ofItem
) that resulted in these issues:Generic
#1796But maybe we're missing some typing/pyright features here? 🤔
Thank you :)
Beta Was this translation helpful? Give feedback.
All reactions