Skip to content

Python keywords as property names produce invalid Python; rest and optional tuples become fixed-length tuples #50

Open

Description

@trackoor

Object types whose property names are Python keywords (such as from, class, in, def, or None) are emitted using class TypedDict syntax that fails to parse in Python and Pyright, and tuple types with rest (...T[]) or optional (T?) elements are emitted as fixed-length Tuple[...] types.

// types.ts
export type Kw = { class: string; from: number; None: boolean; def?: string };
export type RestTuple = [string, ...number[]];
export type OptTuple = [string, number?];

Run with:

npx typescript2python@2.2.0 types.ts > types.py
python3 -c 'import ast; ast.parse(open("types.py").read())'

Actual types.py:

from typing_extensions import NotRequired, Tuple, TypedDict, Union

class Kw(TypedDict):
  class: str
  from: float
  None: bool
  def: NotRequired[str]

RestTuple = Tuple[str,float]

OptTuple = Tuple[str,Union[None,float]]

python3 -c 'import ast; ast.parse(open("types.py").read())' raises SyntaxError: invalid syntax at class: str (line 4), and Pyright rejects ("a",) and ("a", 1, 2) for RestTuple and ("a",) for OptTuple (Tuple size mismatch; expected 2).

Expected types.py:

from typing_extensions import NotRequired, Tuple, TypedDict, Union, Unpack

Kw = TypedDict("Kw", {
  "class": str,
  "from": float,
  "None": bool,
  "def": NotRequired[str]
})

RestTuple = Tuple[str,Unpack[Tuple[float, ...]]]

OptTuple = Union[Tuple[str],Tuple[str,float]]

In src/isValidPythonIdentifier.ts, isValidPythonIdentifier only checks /^[a-zA-Z_][\w]*$/ without excluding Python reserved keywords (keyword.kwlist, including None/True/False and lambda), so parseTypeDefinition does not use the functional TypedDict fallback added in #21; in src/parseInlineType.ts, isTupleType maps typechecker.getTypeArguments(type) directly into Tuple[...] without checking (type as ts.TupleTypeReference).target.elementFlags for rest/variadic or optional elements.

Tested on typescript2python@2.2.0 (npm latest) and main (bb2fa60f) with Node.js v26.13.0, Python 3.11.2, and Pyright 1.1.414.

Credit: https://ucsbplse.github.io/

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions