Stewori / pytypes

Typing-toolbox for Python 3 _and_ 2.7 w.r.t. PEP 484.
Apache License 2.0
200 stars 20 forks source link

stub file load works only across single file #41

Closed gaborbernat closed 6 years ago

gaborbernat commented 6 years ago

Problem presentation

The way the stub file implementation is done it will only work when all imports can be resolved using the Python files. A simple example when this is not the case is type aliases. For example imagine:

# util.pyi
from typing import Union

MagicParam = Union[int, float]
# magic.pyi
from .util import MagicParam

def a() -> MagicParam: ...

Loading magic.pyi will break with an import error of MagicParam as that is not defined inside the corresponding util.py. And given it's a type alias it should not be. As is used solely by the typing system.

The above example works with mypy, following the priority list described in PEP-561 resolution order.

Proposed solution

When loading stub files start with a clean import system, that first searches for pyi files, and if not present fallback to py. I have a prof of concept level of this here https://github.com/gaborbernat/prefer-stubs-python-import. If you think this request is reasonable I can make a PR for it. Thanks!

Stewori commented 6 years ago

Thanks for spotting this issue. You're more than welcome to help out, my current priority is on fixing Python 3.7 support.

Some things to keep in mind:

I cannot tell right now if any of these notes applies to your approach (e.g. I never tried to use contextlib in Jython, maybe it just works). It's just things that might have to be considered. Good luck and feel free to ask for advice on pytypes internals etc if required!

Stewori commented 6 years ago

I hope my comments did not scare you away. Please feel free to go on with a PR, even if it wouldn't consider all the points above right out of the box. We can fix these things together step by step (as far as necessary at all).

gaborbernat commented 6 years ago

@Stewori did not scare me away but me realize my current implementation has conceptional problems. E.g. does not handle forward references at all...

Stewori commented 6 years ago

Note that pytypes has a mechanism to handle forward references: type_util.resolve_fw_decl which takes a module name as (optional) parameter, denoting a module where it looks for declarations of referenced variables. I'm not sure right now if it works with a stub file as module, but if not we should add it there.

gaborbernat commented 6 years ago

I gave this a good thought and decide to do this instead at mypy level :smiley: