Skip to content

Commit 3edfb3b

Browse files
committed
Fix pyi parser to handle trailing commas in namedtuple definitions.
Fixes #434. PiperOrigin-RevId: 274881013
1 parent 92c0c30 commit 3edfb3b

File tree

2 files changed

+67
-2
lines changed

2 files changed

+67
-2
lines changed

pytype/pyi/parser.yy

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -626,11 +626,11 @@ type
626626
$$ = ctx->Call(kNewType, "(NN)", $1, $3);
627627
CHECK($$, @$);
628628
}
629-
| NAMEDTUPLE '(' STRING ',' named_tuple_fields ')' {
629+
| NAMEDTUPLE '(' STRING ',' named_tuple_fields maybe_comma ')' {
630630
$$ = ctx->Call(kNewNamedTuple, "(NN)", $3, $5);
631631
CHECK($$, @$);
632632
}
633-
| COLL_NAMEDTUPLE '(' STRING ',' coll_named_tuple_fields ')' {
633+
| COLL_NAMEDTUPLE '(' STRING ',' coll_named_tuple_fields maybe_comma ')' {
634634
$$ = ctx->Call(kNewNamedTuple, "(NN)", $3, $5);
635635
CHECK($$, @$);
636636
}

pytype/pyi/parser_test.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -725,6 +725,71 @@ def __init__(self, *args, **kwargs) -> None: ...
725725
class X(`namedtuple-X-0`): ...
726726
""")
727727

728+
def test_trailing_comma(self):
729+
self.check("""\
730+
from typing import NamedTuple
731+
Foo = NamedTuple(
732+
"Foo",
733+
[
734+
("a", int),
735+
("b", str),
736+
],
737+
)
738+
""", """\
739+
from typing import Any, Tuple, Type, TypeVar
740+
741+
Foo = `namedtuple-Foo-0`
742+
743+
_Tnamedtuple-Foo-0 = TypeVar('_Tnamedtuple-Foo-0', bound=`namedtuple-Foo-0`)
744+
745+
class `namedtuple-Foo-0`(Tuple[int, str]):
746+
__slots__ = ["a", "b"]
747+
a: int
748+
b: str
749+
_asdict: Any
750+
__dict__: Any
751+
_fields: Any
752+
__getnewargs__: Any
753+
__getstate__: Any
754+
_make: Any
755+
_replace: Any
756+
def __new__(cls: Type[`_Tnamedtuple-Foo-0`], a: int, b: str) -> `_Tnamedtuple-Foo-0`: ...
757+
def __init__(self, *args, **kwargs) -> None: ...
758+
""")
759+
760+
def test_collections_trailing_comma(self):
761+
self.check("""\
762+
from collections import namedtuple
763+
Foo = namedtuple(
764+
"Foo",
765+
[
766+
"a",
767+
"b",
768+
],
769+
)
770+
""", """\
771+
from typing import Any, Tuple, Type, TypeVar
772+
773+
from collections import namedtuple
774+
Foo = `namedtuple-Foo-0`
775+
776+
_Tnamedtuple-Foo-0 = TypeVar('_Tnamedtuple-Foo-0', bound=`namedtuple-Foo-0`)
777+
778+
class `namedtuple-Foo-0`(Tuple[Any, Any]):
779+
__slots__ = ["a", "b"]
780+
a: Any
781+
b: Any
782+
_asdict: Any
783+
__dict__: Any
784+
_fields: Any
785+
__getnewargs__: Any
786+
__getstate__: Any
787+
_make: Any
788+
_replace: Any
789+
def __new__(cls: Type[`_Tnamedtuple-Foo-0`], a, b) -> `_Tnamedtuple-Foo-0`: ...
790+
def __init__(self, *args, **kwargs) -> None: ...
791+
""")
792+
728793
def test_collections_namedtuple(self):
729794
expected = """\
730795
from typing import Any, Tuple, Type, TypeVar

0 commit comments

Comments
 (0)