pytype icon indicating copy to clipboard operation
pytype copied to clipboard

Interface files generate invalid syntax for TypedDict with non-identifier keys

Open SquidDev opened this issue 2 years ago • 1 comments

When pytype emits a TypedDict in a .pyi file, it unconditionally writes a class-style TypedDict. This results in syntax errors if some fields are not identifiers (i.e. keywords or include spaces).

Reproduction steps

Create file_1.py:

from typing import TypedDict

X = TypedDict("X", {"in": str})

and file_2.py:

import file_2

Now typecheck file_2:

$ pytype file_2
File "file_2.py", line 1, in <module>: Couldn't import pyi for 'file_1' [pyi-error]
    File: ".pytype/pyi/file_1.pyi", line 6
  ParseError: invalid syntax

For more details, see https://google.github.io/pytype/errors.html#pyi-error
ninja: build stopped: subcommand failed.
Leaving directory '.pytype'

Looking at file_1.pyi, we can see an (invalid) class-style TypedDict was generated.

# (generated with --quick)

from typing import TypedDict

class X(TypedDict):
    in: str

Reading the discussion in #1184, I assume supporting this is wanted, just not yet implemented? I'm happy to have a look at putting a PR together if that would be helpful?

SquidDev avatar Jun 07 '22 16:06 SquidDev

Yeah, that was an oversight.

I'm happy to have a look at putting a PR together if that would be helpful?

Absolutely, we'd love the help! My guess is that the easiest thing would be to special-case TypedDicts in https://github.com/google/pytype/blob/main/pytype/pytd/printer.py (the module responsible for converting our internal representation of pyi files to text), although @martindemello is the expert in this area.

rchen152 avatar Jun 09 '22 23:06 rchen152