Skip to content

Commit

Permalink
stubgen: preserve PEP 604 Unions in generated pyi files (#14601)
Browse files Browse the repository at this point in the history
When a PEP 604 Union exists in the runtime, stubgen was generating a
`Union[...]` syntax without importing `Union` from `typing`. With this
change, stubgen preserves the ` | `-unions in the output.

Fixes #12929
Closes #13428
Ref #12920
  • Loading branch information
hamdanal authored Feb 7, 2023
1 parent dc03478 commit 725214b
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
4 changes: 4 additions & 0 deletions mypy/stubgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@
TypeList,
TypeStrVisitor,
UnboundType,
UnionType,
get_proper_type,
)
from mypy.visitor import NodeVisitor
Expand Down Expand Up @@ -326,6 +327,9 @@ def visit_none_type(self, t: NoneType) -> str:
def visit_type_list(self, t: TypeList) -> str:
return f"[{self.list_str(t.items)}]"

def visit_union_type(self, t: UnionType) -> str:
return " | ".join([item.accept(self) for item in t.items])

def args_str(self, args: Iterable[Type]) -> str:
"""Convert an array of arguments to strings and join the results with commas.
Expand Down
10 changes: 10 additions & 0 deletions test-data/unit/stubgen.test
Original file line number Diff line number Diff line change
Expand Up @@ -2783,3 +2783,13 @@ T = TypeVar("T", bound=str | None)
from typing import TypeVar

T = TypeVar('T', bound=str | None)


[case testPEP604UnionType]
a: str | int

def f(x: str | None) -> None: ...
[out]
a: str | int

def f(x: str | None) -> None: ...

0 comments on commit 725214b

Please sign in to comment.