Skip to content

Commit

Permalink
fix: handle fixed tuples correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
autumnjolitz committed Jul 23, 2024
1 parent 0930b36 commit f1ab15f
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
8 changes: 6 additions & 2 deletions instruct/typedef.py
Original file line number Diff line number Diff line change
Expand Up @@ -956,13 +956,14 @@ def test_func_homogenous_tuple(value):
test_types = flatten(
(parse_typedef(some_type) for some_type in value_types), eager=True
)
parsed_value_types = tuple(parse_typedef(x) for x in value_types)

def test_func_heterogenous_tuple(value):
if not isinstance(value, container_cls):
return False
if len(value) != len(test_types):
if len(value) != len(parsed_value_types):
return False
for index, (item, item_type) in enumerate(zip(value, test_types)):
for index, (item, item_type) in enumerate(zip(value, parsed_value_types)):
if not isinstance(item, item_type):
return False
return True
Expand Down Expand Up @@ -1194,6 +1195,9 @@ def parse_typedef(
)
type_args = get_args(typehint)
if type_args or as_origin_cls is None:
assert all(
isinstance(x, (type, type(Ellipsis))) or is_typing_definition(x) for x in type_args
), f"{typehint!r} vs {type_args!r}"
if as_origin_cls is not None:
cls = create_custom_type(as_origin_cls, *type_args, check_ranges=check_ranges)
else:
Expand Down
7 changes: 7 additions & 0 deletions tests/test_typedef.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,3 +287,10 @@ def test_parse_typedef_generics():
assert isinstance((1, "str"), parse_typedef(SomeGenericSeq[int, str]))
assert not isinstance((1, 1), parse_typedef(SomeGenericSeq[int, str]))
assert not isinstance((1, 1), parse_typedef(Tuple[int, str]))


def test_strict_heterogenous():
t = parse_typedef(Tuple[Union[Literal["a", "b"], str], Union[int, float]])
assert isinstance(("", -1), t)
assert isinstance(("a", 1.0), t)
assert isinstance(("b", 4), t)

0 comments on commit f1ab15f

Please sign in to comment.