mypy icon indicating copy to clipboard operation
mypy copied to clipboard

stubgen: import `Union` if generated stub code includes

Open eggplants opened this issue 3 years ago • 3 comments

Feature

I would like to insert from typing import Union when generated stub code by stubgen includes Union.

Pitch

ref: #12920

Now:

# Python 3.10.4, mypy 0.960
$ cat test.py
import random


def a() -> int | str:
    if random.random() > 0.5:
        return 1
    else:
        return "hey!"

def b() -> str | None:
    if random.random() > 0.5:
        return "hey!"

$ stubgen test.py
Processed 1 modules
Generated out/test.pyi

$ cat out/test.pyi
def a() -> Union[int, str]: ...
def b() -> Union[str, None]: ...

Expect:

from typing import Union

def a() -> Union[int, str]: ...
def b() -> Union[str, None]: ...

eggplants avatar Jun 02 '22 13:06 eggplants

Thanks! I expect this is an easy fix (just need to ad some function call to make stubgen emit the import), so if you're willing to dive into the code, feel free to make a PR.

JelleZijlstra avatar Jun 02 '22 15:06 JelleZijlstra

OK, I'll try it...

eggplants avatar Jun 04 '22 02:06 eggplants

Is there any update on this fix?

bo-dani avatar Jan 04 '23 14:01 bo-dani

If no one else is working on this I can pick it up

sguidotti avatar Feb 07 '23 05:02 sguidotti

@sguidotti

@hamdanal has already created: #14601

eggplants avatar Feb 07 '23 06:02 eggplants