Python package to enforce optional dependencies
Project description
Necessary
Python package to enforce optional dependencies.
How to Use
Simply use necessary.necessary
to conditionally import a module.
from necessary import necessary
if necessary('torch'):
# this will raise an error if
# torch is not installed
import torch
If you want to just soft fail when a necessary module is not available (that is, have necessary return False
), use soft_check
:
try:
# assuming torch is not installed
necessary('torch')
except ImportError:
out = necessary('torch', soft_check=True)
print(out) # this prints False
If you want to request a minimum version, use min_version
:
if necessary('torch', min_version='1.12.0'):
# this will raise an error if
# torch is not installed or if
# the installed version is less than 0.12.0
import torch
Issues with Pylance
If you use Pylance language server with Pyright, Pylance might complain that the imported module might be out of scope. As a workaround, combine necessary
with TYPE_CHECKING
:
from typing import TYPE_CHECKING
from necessary import necessary
if necessary('torch') or TYPE_CHECKING:
import torch
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
necessary-0.1.1.tar.gz
(6.8 kB
view hashes)
Built Distribution
Close
Hashes for necessary-0.1.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | cae3c0c2eb9d541667e5662834151ede9c100e7dfee34d4c2de31b60bb6a7f3d |
|
MD5 | 883bd0bd1f7d90ceae285b0f3f801f62 |
|
BLAKE2b-256 | 1733e3d188571686f5557698d5d38986307853c876c379d53e2731423eba1bb6 |