pyright/docs/import-resolution.md
2019-04-28 12:59:19 -07:00

2.9 KiB
Raw Blame History

Import Resolution

Pyright resolves external imports based on several configuration settings. If a venvPath and venv are specified, these are used to locate the site-packages directory within the virtual environment.

If no venvPath is specified, Pyright falls back to the paths found in the default python interpreters search paths (or the python intpreter pointed to by the “python.pythonPath” setting in VS Code). Only directory-based paths are supported (as opposed to zip files or other loader packages).

The Pyright configuration file supports “execution environment” definitions, each of which can define additional paths. These are searched in addition to the venv or PYTHONPATH directories.

If Pyright is reporting import resolution errors, additional diagnostic information may help you determine why. If you are using the command-line version, try adding the “--verbose” switch. If you are using the VS Code extension, look at the “Output” window (View -> Output) and choose the “Pyright” view from the popup menu.

Importance of Type Stub Files

Regardless of the search path, Pyright always attempts to resolve an import with a type stub (“.pyi”) file before falling back to a python source (“.py”) file. If a type stub cannot be located for an external import, that import will be treated as a “black box” for purposes of type analysis. Any symbols imported from these modules will be of type “Unknown”, and wildcard imports (of the form from foo import *) will not populate the modules namespace with specific symbol names.

Why does Pyright not attempt to determine types from imported python sources? There are several reasons.

  1. Imported libraries can be quite large, so analyzing them would require significant time and computation.
  2. Some libraries are thin shims on top of native (C++) libraries. Little or no type information would be inferable in these cases.
  3. Some libraries override Pythons default loader logic. Static analysis is not possible in these cases.
  4. Type information inferred from source files is often of low value because many types cannot be inferred correctly. Even if concrete types can be inferred, generic type definitions cannot.
  5. Type analysis would expose all symbols from an imported module, even those that are not meant to be exposed by the author. Unlike many other languages, Python offers no way of differentiating between a symbol that is meant to be exported and one that isnt.

If youre serious about static type checking for your Python source base, its highly recommended that you use type stub files for all external imports. If you are unable to find a type stub for a particular library, the recommended approach is to create a custom type stub file that defines the portion of that modules interface used by your code. Hopefully, more library authors will provide type stub files in the future.