Add torch to `setup_requires` & dynamic import to prevent import errors when installing via pip
The problem
When trying to install BasicSR as part of of requirements.txt file, install fails if torch is not already installed It is required in the setup phase This behaviour can cause unexpected errors in depending on the pip install order
The Solution
-
In this PR I added
setup_requiresparameter to indicate that torch is required for the setup phase -
Because torch is required only when building the cuda extensions I moved the import to be dynamic with a clear error message for the user
References
- https://github.com/xinntao/BasicSR/issues/499
please approve @xinntao
This doesn't work for me. When torch is not installed, even when not building the extensions, the line cmdclass={'build_ext': BuildExtension}, at the end of setup() throws a NameError: name 'BuildExtension' is not defined.
A slightly edited working version here: https://github.com/JCBrouwer/BasicSR/blob/feature/dynamic-import-torch/setup.py
You can use pyproject.toml to make torch available before setup.py is processed.
Something like:
# pyproject.toml
[build-system]
requires = ["cython", "numpy", "torch", "setuptools"]
build-backend = "setuptools.build_meta"
build-backend = "setuptools.build_meta" will remove the CWD from sys.path inside your setup.py file.
If you need CWD in sys.path you can also use build-backend = "setuptools.build_meta:__legacy__".