Skip to content

Refer to SPEC for stub usage #29

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 16, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 7 additions & 34 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,42 +72,15 @@ from .edges import (sobel, scharr, prewitt, roberts,

Except that all subpackages (such as `rank`) and functions (such as `sobel`) are loaded upon access.

### Lazily load subpackages and functions from type stubs
### Type checkers

Because static type checkers and IDEs will likely be unable to find your
dynamically declared imports, you can use a [type
stub](https://mypy.readthedocs.io/en/stable/stubs.html) (`.pyi` file) to declare
the imports. However, if used with the above pattern, this results in code
duplication, as you now need to declare your submodules and attributes in two places.
Static type checkers and IDEs cannot infer type information from
lazily loaded imports. As a workaround you can load [type
stubs](https://mypy.readthedocs.io/en/stable/stubs.html) (`.pyi`
files) with `lazy.attach_stub`.

You can infer the `submodules` and `submod_attrs` arguments (explicitly provided
above to `lazy.attach`) from a stub adjacent to the `.py` file by using the
`lazy.attach_stub` function.

Carrying on with the example above:

The `skimage/filters/__init__.py` module would be declared as such:

```python
from ..util import lazy

__getattr__, __dir__, __all__ = lazy.attach_stub(__name__, __file__)
```

... and the adjacent `skimage/filters/__init__.pyi` stub would contain:

```python
from . import rank
from ._gaussian import gaussian, difference_of_gaussians
from .edges import (sobel, scharr, prewitt, roberts,
laplace, farid)
```

Note that in order for this to work, you must be sure to include the `.pyi`
files in your package distribution. For example, with setuptools, you would need
to [set the `package_data`
option](https://setuptools.pypa.io/en/latest/userguide/datafiles.html#package-data)
to include `*.pyi` files.
The SPEC [describes this workaround in more
detail](https://scientific-python.org/specs/spec-0001/#type-checkers).

### Early failure

Expand Down