python / mypy

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

Preserve annotations and inferred types when generating stubs #3475

Open JukkaL opened 7 years ago

JukkaL commented 7 years ago

If a user maintains a 3rd party library module that is type checked using mypy, there is no easy to way to automatically generate annotated typeshed stubs for that library, even though this could be pretty useful. We could perhaps extend stubgen to do this job.

Here's how this could work internally:

The main difference from previous stubgen related proposals would be the inclusion of inferred types in the stubs. For example, consider this program:

x = 0
a = [x]

The generated stub could look like this:

from typing import List

x: int
a: List[int]

Here are a few things that complicate this task:

ilevkivskyi commented 7 years ago

There is an existing PR https://github.com/python/mypy/pull/3169 for improving stubgen. But it only preserves existing annotations, type aliases, and TypeVars (i.e. no inferred annotations).

JelleZijlstra commented 7 years ago

I was thinking about this in the context of python/typing#84.

An alternative for fully annotated libraries could be to just install their full code in the "stubs" directory, so we don't have to generate separate stub files. However, that may slow down mypy and it may cause problems when user code is type checked with more restrictive flags than the library.

JukkaL commented 7 years ago

User code may also be fail to type check because of differences between mypy versions. Stubs are more likely to be compatible across mypy versions than actual code.