I am currently using a Python library (x) that does not come with type hints. I've opted to add stub files for the x methods that I use in my project like this:
MyProject_1/
stubs/
x/
__init__.pyi # Contains type hints for any attributes of `x`.
package_1/
package_1_main.py # Imports `x`.
__init__.py
py.typed # Indicates package 1 type hints are specified inline.
setup.py # Specifies `x` as a dependency under `install_requires` and `py.typed` under `package_data`.
Then in the MyProject_1 directory, I run MYPYPATH=stubs mypy ..
If package_1_main.py imports x, then mypy successfully type hints the x imports based on stubs/x. All is good here.
Now I've made another project MyProject_2 that depends on MyProject_1 My_Project_2 successfully uses the inline type hints specified in package_1_main.py because of the py.typed under package_1.
The problem is that MyProject_2 does not pick up on stubs/x. Since x is a transitive dependency of MyProject_2 through MyProject_1, I have the ability to use x in MyProject_2. However, this is without the type hints specified under stubs/x.
There are 3 ways I can imagine being able to use these stubs (and thus access the type hints of x):
-
Add the
stubsdirectory underMyProject_1to theMYPYPATHwhen runningmypy .inMyProject_2. Downside of this is it depends on howMyProject_1was installed throughpip, andstubswill have to be made as part of the distributed package data insetup.py. -
Copy the
stubsdirectory underMyProject_1toMyProject_2, keeping them manually in sync. Downside of this is overhead in maintenance. -
Make a third project called
MyProject_Stubs, dedicated to keeping the stub files for any project depending onx, either transitively or directly. Downside of this is a dedicated project just for stubs.
Are there any other approaches I could consider? And for the slightly opinionated part: which one of these approaches seems to have the greatest net advantage?
from How to share stubs for type hinting transitively?
No comments:
Post a Comment