Skip to content

Commit 725214b

Browse files
authored
stubgen: preserve PEP 604 Unions in generated pyi files (#14601)
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
1 parent dc03478 commit 725214b

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

Diff for: mypy/stubgen.py

+4
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@
134134
TypeList,
135135
TypeStrVisitor,
136136
UnboundType,
137+
UnionType,
137138
get_proper_type,
138139
)
139140
from mypy.visitor import NodeVisitor
@@ -326,6 +327,9 @@ def visit_none_type(self, t: NoneType) -> str:
326327
def visit_type_list(self, t: TypeList) -> str:
327328
return f"[{self.list_str(t.items)}]"
328329

330+
def visit_union_type(self, t: UnionType) -> str:
331+
return " | ".join([item.accept(self) for item in t.items])
332+
329333
def args_str(self, args: Iterable[Type]) -> str:
330334
"""Convert an array of arguments to strings and join the results with commas.
331335

Diff for: test-data/unit/stubgen.test

+10
Original file line numberDiff line numberDiff line change
@@ -2783,3 +2783,13 @@ T = TypeVar("T", bound=str | None)
27832783
from typing import TypeVar
27842784

27852785
T = TypeVar('T', bound=str | None)
2786+
2787+
2788+
[case testPEP604UnionType]
2789+
a: str | int
2790+
2791+
def f(x: str | None) -> None: ...
2792+
[out]
2793+
a: str | int
2794+
2795+
def f(x: str | None) -> None: ...

0 commit comments

Comments
 (0)