Skip to content

[mypyc] Fixing iteration over NamedTuple objects. #18254

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

Merged
merged 1 commit into from
Dec 6, 2024
Merged
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: 17 additions & 5 deletions mypyc/irbuild/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
Type,
TypedDictType,
TypeOfAny,
TypeVarLikeType,
UninhabitedType,
UnionType,
get_proper_type,
Expand Down Expand Up @@ -910,11 +911,22 @@ def get_sequence_type_from_type(self, target_type: Type) -> RType:
return RUnion.make_simplified_union(
[self.get_sequence_type_from_type(item) for item in target_type.items]
)
assert isinstance(target_type, Instance), target_type
if target_type.type.fullname == "builtins.str":
return str_rprimitive
else:
return self.type_to_rtype(target_type.args[0])
elif isinstance(target_type, Instance):
if target_type.type.fullname == "builtins.str":
return str_rprimitive
else:
return self.type_to_rtype(target_type.args[0])
# This elif-blocks are needed for iterating over classes derived from NamedTuple.
elif isinstance(target_type, TypeVarLikeType):
return self.get_sequence_type_from_type(target_type.upper_bound)
elif isinstance(target_type, TupleType):
# Tuple might have elements of different types.
rtypes = {self.mapper.type_to_rtype(item) for item in target_type.items}
if len(rtypes) == 1:
return rtypes.pop()
else:
return RUnion.make_simplified_union(list(rtypes))
assert False, target_type

def get_dict_base_type(self, expr: Expression) -> list[Instance]:
"""Find dict type of a dict-like expression.
Expand Down
26 changes: 26 additions & 0 deletions mypyc/test-data/run-loops.test
Original file line number Diff line number Diff line change
Expand Up @@ -545,3 +545,29 @@ def test_range_object() -> None:
r4 = range(4, 12, 0)
except ValueError as e:
assert "range() arg 3 must not be zero" in str(e)

[case testNamedTupleLoop]
from collections.abc import Iterable
from typing import NamedTuple, Any
from typing_extensions import Self


class Vector2(NamedTuple):
x: int
y: float

@classmethod
def from_iter(cls, iterable: Iterable[Any]) -> Self:
return cls(*iter(iterable))

def __neg__(self) -> Self:
return self.from_iter(-c for c in self)

[file driver.py]
import native
print(-native.Vector2(2, -3.1))
print([x for x in native.Vector2(4, -5.2)])

[out]
Vector2(x=-2, y=3.1)
\[4, -5.2]
Loading