Python package to enforce optional dependencies
Project description
Necessary
Python package to enforce optional dependencies.
Install with:
pip install necessary
How to Use
Simply use necessary.necessary
to get a context manager import a module.
from necessary import necessary
with necessary('torch'):
# this will raise a nicely written 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
:
try:
# assuming torch is not installed
necessary('torch')
except ImportError:
out = necessary('torch', soft=True)
assert out is False
If you want to request a minimum version, use min_version
:
with necessary(('torch', '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
You can also check multiple packages in the same necessary
call:
with necessary([('torch', '1.12.0'), 'numpy']):
# this will raise an error if torch >= 1.12.0 or numpy are not installed
import torch
import numpy
Finally, we can customize the message that is raised if a necessary module is not installed; use {module_name}
and {module_version}
to insert the module name and version respectively.
with necessary('torch', message='I am missing {module_name}/{module_version}'):
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.2.2.tar.gz
(7.9 kB
view hashes)
Built Distribution
Close
Hashes for necessary-0.2.2-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | feb83114959cc60def102b5bdcc4f4d6bacf2d2964bf4fb57255119ffc7bc026 |
|
MD5 | 74666fe0b7721b811c9313f83027368f |
|
BLAKE2b-256 | 9e01ffa5263130ae7350927bb9a2db2544f0202408f000a439290523318da035 |