Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 13 additions & 9 deletions pyrefly/lib/alt/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2336,15 +2336,19 @@ impl<'a, Ans: LookupAnswer> AnswersSolver<'a, Ans> {
Some(&|| ErrorContext::Index(self.for_display(base.clone()))),
),
Type::Quantified(ref q) if q.is_type_var() && q.restriction().is_restricted() => {
self.call_method_or_error(
&base,
&dunder::GETITEM,
range,
&[CallArg::expr(slice)],
&[],
errors,
Some(&|| ErrorContext::Index(self.for_display(base.clone()))),
)
match q.restriction() {
Restriction::Bound(bound) => {
self.subscript_infer_for_type(bound, slice, range, errors)
}
Restriction::Constraints(constraints) => {
self.unions(constraints.map(|constraint| {
self.subscript_infer_for_type(constraint, slice, range, errors)
}))
}
Restriction::Unrestricted => {
unreachable!("restricted TypeVar cannot be unrestricted")
}
}
}
Type::TypedDict(typed_dict) => {
let key_ty = self.expr_infer(slice, errors);
Expand Down
35 changes: 35 additions & 0 deletions pyrefly/lib/test/typed_dict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2536,3 +2536,38 @@ def f(x: str) -> TD[int] | TD[str]:
return TD(value=x)
"#,
);

testcase!(
test_constrained_type_var_typed_dict_index,
r#"
from typing import Generic, TypedDict, TypeVar, assert_type

class DeviceInfo(TypedDict):
name: str
address: str
rssi: int

class ExtendedDeviceInfo(TypedDict):
name: str
address: str
rssi: int
manufacturer: str

NAME = "name"
ADDRESS = "address"

T = TypeVar("T", DeviceInfo, ExtendedDeviceInfo)

class DeviceIndex(Generic[T]):
def __init__(self) -> None:
self.by_name: dict[str, list[T]] = {}

def add(self, device: T) -> None:
name = device[NAME]
assert_type(name, str)
self.by_name.setdefault(name, []).append(device)

def lookup(self, device: T) -> str:
return device[ADDRESS]
"#,
);
Loading