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 HERERunning 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. |
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" |
The
castin 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
cheeseinstance variable, so its type is inferred based on the values assigned to it within theParentclass. 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 = 1to imply thatfoois limited to just1; you'd expect thatfoowould accept anyint.For more details about inference, refer to this documentation.
If your…