Skip to main content

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


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)

Uploaded Source

Built Distribution

necessary-0.1.1-py3-none-any.whl (7.0 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page