We develop a Python library that contains a function expecting a numlike parameter. We specify this in our signature and make use of python type hints:
def cool(value: float | int | List[float | int])
During runtime, we noticed it's fine to pass in numpy number types as well, e.g. np.float16(1.2345). So we thought: why not incorporate "numpy number types" into our signature as this would be beneficial for the community that will use our library.
However, we don't want numpy as dependency in our project. We'd like to only signify in the method signature that we can take a float, int, a list of them OR any "numpy number type". If the user hasn't installed numpy on their system, they should still be able to use our library and just ignore that they could possibly pass in a "numpy number type" as well.
We don't want to depend on numpy as we don't use it in our library (except for allowing their types in our method signature). So why include it in our dependency graph? There's no reason to do so. One dependency less is better.
>=3.8.setuptools>=69.0.)Ctrl + Space) when typing cool( in an IDE, e.g. VSCode.pyproject.toml looks like.[project.optional-dependencies] for the pyproject.toml file, see here. However, it remains unclear how this optional dependencies declaration helps us in providing optional numpy datatypes in our method signatures.numpy provides the numpy.typing type annotations. Is it somehow possible to only depend on this subpackage?Defer evaluation of annotations, and only import numpy conditionally.
from __future__ import annotations
import typing as t
if t.TYPE_CHECKING:
import numpy as np
def cool(value: int | np.floating | etc ...):
...
Now the numpy dependency is only necessary when type-checking.
See PEP 563 – Postponed Evaluation of Annotations
numpyprovides thenumpy.typingtype annotations. Is it somehow possible to only depend on this subpackage?
No, this is not possible.
We've noticed the option
[project.optional-dependencies]for thepyproject.tomlfile ...
It doesn't really help you much here. It could still be useful if you wanted "extra" dependencies which the user can opt-in for, e.g.:
pip install mypkg # install with required dependencies
pip install mypkg[typing] # install with extra dependencies such as numpy
Then you could use this to easily install the package along with the soft-deps in your CI, for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With