Skip to content

Allow class-based NamedTuple syntax in semantic analyzer for stubs in pre-3.6 mode #3464

Closed

Description

@gvanrossum

See python/typeshed#1336 (comment)

Not very important, but would be nice if stubs could use

class A(NamedTuple):
    x: int
    y: str

instead if

A = NamedTuple('A', [('x', int), ('y', str)])

Activity

  1. srittau commented on Oct 7, 2019

    @srittau
    Contributor

    Had this come up in python/typeshed#3278.

  2. JukkaL commented on Oct 7, 2019

    @JukkaL
    Collaborator

    This seems to be the relevant code (in mypy/semanal_namedtuple.py):

        def check_namedtuple_classdef(
                self, defn: ClassDef) -> Optional[Tuple[List[str], List[Type], Dict[str, Expression]]]:
            """Parse and validate fields in named tuple class definition.
    
            Return a three tuple:
              * field names
              * field types
              * field default values
            or None, if any of the types are not ready.
            """
            if self.options.python_version < (3, 6):
                self.fail('NamedTuple class syntax is only supported in Python 3.6', defn)
                return [], [], {}
    ...

    Also, there is is_typeshed_stub_file() in SemanticAnalyzerInterface which isn't quite what we need. A similar property could be added for is_stub_file(), and then the rest should be easy.

    Anybody want to write a PR?

  3. added a commit that references this issue on Oct 7, 2019
    4f0ae4d
  4. srittau commented on Oct 7, 2019

    @srittau
    Contributor

    PR in #7646.

  5. added a commit that references this issue on Oct 7, 2019
    e4d99c6
  6. gvanrossum commented on Oct 7, 2019

    @gvanrossum
    MemberAuthor

    Do we know if this is supported by type checkers other than mypy?

  7. srittau commented on Oct 30, 2019

    @srittau
    Contributor

    We checked this in python/typeshed#3321 and pytype, pyre, and pyright, PyCharm, and the Microsoft Language Server for Python all support this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions