python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.56k stars 2.84k forks source link

Stub generation adds too many explicit re-exports #18113

Open henzef opened 2 weeks ago

henzef commented 2 weeks ago

Bug Report

mypy stubgen re-exports more names than needed (despite --export-less). It seems that imports that are only used in function parameter type annotations (see FirstErrorType below) are always re-exported and imports from 'if TYPE_CHECKING' clauses (see SecondErrorType below) as well.

To Reproduce

# example.py
from typing import TYPE_CHECKING
from b import FirstErrorType, WorkingType
if TYPE_CHECKING:
    from c import SecondErrorType

def foobar(one: FirstErrorType, two: "SecondErrorType") -> None:
    pass

def spamandeggs() -> WorkingType:
    return WorkingType()

Expected Behavior

Nether FirstErrorType nor SecondErrorType should be re-exported according to the documentation of the --export-less switch, which states

only export imported names that are not referenced in the module that contains the import.

Actual Behavior

the output of stubgen --export-less example.py

# example.pyi
from b import FirstErrorType as FirstErrorType, WorkingType
from c import SecondErrorType as SecondErrorType

def foobar(one: FirstErrorType, two: SecondErrorType) -> None: ...
def spamandeggs() -> WorkingType: ...

Your Environment

henzef commented 2 weeks ago

Only semi-related remark: It would be helpful if stubgen could be configured to only re-export names that are already explicitly re-exported in the source file. This would allow me to workaround this issue and would also fix #2190

jorenham commented 2 weeks ago

it also does this if there is an explicit __all__