optpkg

Routines to support optional packages

optional_package(name[, trip_msg, min_version])

Return package-like thing and module setup for package name

optional_package

nibabel.optpkg.optional_package(name, trip_msg=None, min_version=None)

Return package-like thing and module setup for package name

Parameters:
namestr

package name

trip_msgNone or str

message to give when someone tries to use the return package, but we could not import it at an acceptable version, and have returned a TripWire object instead. Default message if None.

min_versionNone or str or Version or callable

If None, do not specify a minimum version. If str, convert to a packaging.version.Version. If str or Version compare to version of package name with min_version <= pkg.__version__. If callable, accepts imported pkg as argument, and returns value of callable is True for acceptable package versions, False otherwise.

Returns:
pkg_likemodule or TripWire instance

If we can import the package, return it. Otherwise return an object raising an error when accessed

have_pkgbool

True if import for package was successful, false otherwise

module_setupfunction

callable usually set as setup_module in calling namespace, to allow skipping tests.

Examples

Typical use would be something like this at the top of a module using an optional package:

>>> from nibabel.optpkg import optional_package
>>> pkg, have_pkg, setup_module = optional_package('not_a_package')

Of course in this case the package doesn’t exist, and so, in the module:

>>> have_pkg
False

and

>>> pkg.some_function() 
Traceback (most recent call last):
    ...
TripWireError: We need package not_a_package for these functions,
    but ``import not_a_package`` raised an ImportError

If the module does exist - we get the module

>>> pkg, _, _ = optional_package('os')
>>> hasattr(pkg, 'path')
True

Or a submodule if that’s what we asked for

>>> subpkg, _, _ = optional_package('os.path')
>>> hasattr(subpkg, 'dirname')
True