Type alias defined in parent seems to be lost in children? #10757
-
With this shortest example I could make up: from typing import Literal, cast
type Cheese = Literal["camenbert"]
def melt_cheese(cheese: Cheese) -> str: ...
class Parent:
def __init__(self):
self.cheese = cast(Cheese, "camenbert") # SEE BELOW
class Child(Parent):
def __init__(self):
super().__init__()
melt_cheese(self.cheese) # ERROR HERE Running pyright tells me:
It is as if in The workaround is easy (add a cast), but by experience, I am probably not understanding something right. Pyright 1.1.403, and python 3.13.0, via uv. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The You haven't provided a type declaration for the For more details about inference, refer to this documentation. If your intent is for class Parent:
def __init__(self):
self.cheese: Cheese = "camenbert" |
Beta Was this translation helpful? Give feedback.
The
cast
in this case does nothing because the type of the expression"camenbert"
is alreadyLiteral["camenbert"]
. Casting it to the same type is therefore a no-op.You haven't provided a type declaration for the
cheese
instance variable, so its type is inferred based on the values assigned to it within theParent
class. The sole assignment is assigning a value of typeLiteral["camenbert"]
, but literals are widened to their non-literal counterpart when inferring types. After all, you would not generally expect the statementself.foo = 1
to imply thatfoo
is limited to just1
; you'd expect thatfoo
would accept anyint
.For more details about inference, refer to this documentation.
If your…