Skip to content

Imports

feu.imports

Contain utilities to manage optional dependencies.

This is a port of coola.utils.imports: package.py (availability checks and MissingPackageError), optional.py (the optional libraries of feu) and lazy.py (lazy_exports).

feu.imports.MissingPackageError

Bases: ModuleNotFoundError, RuntimeError

Raised when an optional package is required but not installed.

It is a ModuleNotFoundError (so except ImportError works as expected). It also derives from RuntimeError, which this error used to be, so existing except RuntimeError code keeps working.

Example
>>> from feu.imports import MissingPackageError, check_package
>>> try:
...     check_package("not_an_installed_package")
... except ImportError as error:
...     print(type(error).__name__, error.name)
...
MissingPackageError not_an_installed_package

feu.imports.availability_cache

availability_cache(fn: F) -> F

Cache the result of an availability check and register it, so clear_availability_caches can reset it.

Use it instead of functools.cache on the functions that check if a package is available.

Parameters:

Name Type Description Default
fn F

The availability check to cache.

required

Returns:

Type Description
F

The cached function, which has a cache_clear method.

Example
>>> from feu.imports import availability_cache
>>> @availability_cache
... def is_my_package_available() -> bool:
...     return True
...
>>> is_my_package_available()
True

feu.imports.check_click

check_click() -> None

Check if the click package is installed.

Raises:

Type Description
MissingPackageError

if the click package is not installed. The message gives the command to install it.

Example
>>> from feu.imports import check_click
>>> check_click()  # doctest: +SKIP

feu.imports.check_git

check_git() -> None

Check if the git package is installed.

Raises:

Type Description
MissingPackageError

if the git package is not installed. The message gives the command to install it (gitpython).

Example
>>> from feu.imports import check_git
>>> check_git()  # doctest: +SKIP

feu.imports.check_package

check_package(
    package: str, *, install: str | None = None
) -> None

Check if the given package is installed and can be imported.

Parameters:

Name Type Description Default
package str

The package name.

required
install str | None

The name to give to pip install when it differs from package. By default, it is package.

None

Raises:

Type Description
MissingPackageError

if the package is not available.

Example
>>> from feu.imports import check_package
>>> check_package("os")

feu.imports.check_requests

check_requests() -> None

Check if the requests package is installed.

Raises:

Type Description
MissingPackageError

if the requests package is not installed. The message gives the command to install it.

Example
>>> from feu.imports import check_requests
>>> check_requests()  # doctest: +SKIP

feu.imports.check_rich

check_rich() -> None

Check if the rich package is installed.

Raises:

Type Description
MissingPackageError

if the rich package is not installed. The message gives the command to install it.

Example
>>> from feu.imports import check_rich
>>> check_rich()  # doctest: +SKIP

feu.imports.clear_availability_caches

clear_availability_caches() -> None

Clear the cached results of the availability checks.

package_available, module_available and the is_<package>_available functions cache their result, so the availability of a package cannot change during the life of the process. Call this function to force the checks to run again, for example in a test that changes sys.modules or sys.path.

The functions to clear are the ones decorated with availability_cache, so there is no list to maintain.

Example
>>> from feu.imports import clear_availability_caches
>>> clear_availability_caches()

feu.imports.is_click_available

is_click_available() -> bool

Indicate if the click package is installed and can be imported.

Returns:

Type Description
bool

True if click is available otherwise False.

Example
>>> from feu.imports import is_click_available
>>> isinstance(is_click_available(), bool)
True

feu.imports.is_git_available

is_git_available() -> bool

Indicate if the git package is installed and can be imported.

Returns:

Type Description
bool

True if git is available otherwise False.

Example
>>> from feu.imports import is_git_available
>>> isinstance(is_git_available(), bool)
True

feu.imports.is_requests_available

is_requests_available() -> bool

Indicate if the requests package is installed and can be imported.

Returns:

Type Description
bool

True if requests is available otherwise False.

Example
>>> from feu.imports import is_requests_available
>>> isinstance(is_requests_available(), bool)
True

feu.imports.is_rich_available

is_rich_available() -> bool

Indicate if the rich package is installed and can be imported.

Returns:

Type Description
bool

True if rich is available otherwise False.

Example
>>> from feu.imports import is_rich_available
>>> isinstance(is_rich_available(), bool)
True

feu.imports.lazy_exports

lazy_exports(
    package: str,
    exports: Mapping[str, str],
    namespace: dict[str, Any],
) -> tuple[Callable[[str], Any], Callable[[], list[str]]]

Create the __getattr__ and __dir__ of a package that imports some of its names when they are used.

The names are in the __all__ of the package, so from package import name works as usual, but the module that defines a name is imported the first time the name is used. This avoids importing the optional libraries that a module needs when the package is imported.

Parameters:

Name Type Description Default
package str

The name of the package, usually __name__.

required
exports Mapping[str, str]

The module that defines each lazy name.

required
namespace dict[str, Any]

The namespace of the package, usually globals(). A name is added to it when it is imported, so the next access does not call __getattr__.

required

Returns:

Type Description
Callable[[str], Any]

The __getattr__ and __dir__ functions of the package.

Callable[[], list[str]]

The returned __getattr__ raises an AttributeError if the

tuple[Callable[[str], Any], Callable[[], list[str]]]

name is not in exports.

Example
>>> namespace = {}
>>> getattr_, dir_ = lazy_exports("example", {"OrderedDict": "collections"}, namespace)
>>> getattr_("OrderedDict")
<class 'collections.OrderedDict'>
>>> "OrderedDict" in namespace
True

feu.imports.module_available

module_available(name: str) -> bool

Indicate if a module is available or not.

The module is imported to check that it works, so a package that is installed but broken is reported as not available. The result is cached; use clear_availability_caches to reset it.

Parameters:

Name Type Description Default
name str

The module name to check.

required

Returns:

Type Description
bool

True if the module is available, otherwise False.

Example
>>> from feu.imports import module_available
>>> module_available("os")
True
>>> module_available("os.missing")
False
>>> module_available("missing.module")
False

feu.imports.package_available

package_available(name: str) -> bool

Indicate if a package is installed or not.

The package is only looked up (it is not imported), so a package that is installed but broken is reported as available. Use module_available to check that a module can be imported.

Parameters:

Name Type Description Default
name str

The package name to check.

required

Returns:

Type Description
bool

True if the package is available, otherwise False.

Example
>>> from feu.imports import package_available
>>> package_available("os")
True
>>> package_available("missing_package")
False

feu.imports.raise_package_missing_error

raise_package_missing_error(
    package: str, *, install: str | None = None
) -> Never

Raise a MissingPackageError for a missing package.

Parameters:

Name Type Description Default
package str

The name of the missing package.

required
install str | None

The name to give to pip install when it differs from package. By default, it is package.

None

Raises:

Type Description
MissingPackageError

Always raised to indicate the package is missing.

Example
>>> from feu.imports import raise_package_missing_error
>>> raise_package_missing_error("numpy")  # doctest: +SKIP

feu.imports.package

Contain utilities to manage optional dependencies.

feu.imports.package.MissingPackageError

Bases: ModuleNotFoundError, RuntimeError

Raised when an optional package is required but not installed.

It is a ModuleNotFoundError (so except ImportError works as expected). It also derives from RuntimeError, which this error used to be, so existing except RuntimeError code keeps working.

Example
>>> from feu.imports import MissingPackageError, check_package
>>> try:
...     check_package("not_an_installed_package")
... except ImportError as error:
...     print(type(error).__name__, error.name)
...
MissingPackageError not_an_installed_package

feu.imports.package.availability_cache

availability_cache(fn: F) -> F

Cache the result of an availability check and register it, so clear_availability_caches can reset it.

Use it instead of functools.cache on the functions that check if a package is available.

Parameters:

Name Type Description Default
fn F

The availability check to cache.

required

Returns:

Type Description
F

The cached function, which has a cache_clear method.

Example
>>> from feu.imports import availability_cache
>>> @availability_cache
... def is_my_package_available() -> bool:
...     return True
...
>>> is_my_package_available()
True

feu.imports.package.check_package

check_package(
    package: str, *, install: str | None = None
) -> None

Check if the given package is installed and can be imported.

Parameters:

Name Type Description Default
package str

The package name.

required
install str | None

The name to give to pip install when it differs from package. By default, it is package.

None

Raises:

Type Description
MissingPackageError

if the package is not available.

Example
>>> from feu.imports import check_package
>>> check_package("os")

feu.imports.package.clear_availability_caches

clear_availability_caches() -> None

Clear the cached results of the availability checks.

package_available, module_available and the is_<package>_available functions cache their result, so the availability of a package cannot change during the life of the process. Call this function to force the checks to run again, for example in a test that changes sys.modules or sys.path.

The functions to clear are the ones decorated with availability_cache, so there is no list to maintain.

Example
>>> from feu.imports import clear_availability_caches
>>> clear_availability_caches()

feu.imports.package.module_available

module_available(name: str) -> bool

Indicate if a module is available or not.

The module is imported to check that it works, so a package that is installed but broken is reported as not available. The result is cached; use clear_availability_caches to reset it.

Parameters:

Name Type Description Default
name str

The module name to check.

required

Returns:

Type Description
bool

True if the module is available, otherwise False.

Example
>>> from feu.imports import module_available
>>> module_available("os")
True
>>> module_available("os.missing")
False
>>> module_available("missing.module")
False

feu.imports.package.package_available

package_available(name: str) -> bool

Indicate if a package is installed or not.

The package is only looked up (it is not imported), so a package that is installed but broken is reported as available. Use module_available to check that a module can be imported.

Parameters:

Name Type Description Default
name str

The package name to check.

required

Returns:

Type Description
bool

True if the package is available, otherwise False.

Example
>>> from feu.imports import package_available
>>> package_available("os")
True
>>> package_available("missing_package")
False

feu.imports.package.raise_package_missing_error

raise_package_missing_error(
    package: str, *, install: str | None = None
) -> Never

Raise a MissingPackageError for a missing package.

Parameters:

Name Type Description Default
package str

The name of the missing package.

required
install str | None

The name to give to pip install when it differs from package. By default, it is package.

None

Raises:

Type Description
MissingPackageError

Always raised to indicate the package is missing.

Example
>>> from feu.imports import raise_package_missing_error
>>> raise_package_missing_error("numpy")  # doctest: +SKIP

feu.imports.optional

Contain the availability checks of the optional libraries.

is_<package>_available indicates if a library can be imported and check_<package> raises a MissingPackageError if it cannot. The libraries are the optional dependencies of feu: click, git (installed with gitpython), requests and rich.

feu.imports.optional.check_click

check_click() -> None

Check if the click package is installed.

Raises:

Type Description
MissingPackageError

if the click package is not installed. The message gives the command to install it.

Example
>>> from feu.imports import check_click
>>> check_click()  # doctest: +SKIP

feu.imports.optional.check_git

check_git() -> None

Check if the git package is installed.

Raises:

Type Description
MissingPackageError

if the git package is not installed. The message gives the command to install it (gitpython).

Example
>>> from feu.imports import check_git
>>> check_git()  # doctest: +SKIP

feu.imports.optional.check_requests

check_requests() -> None

Check if the requests package is installed.

Raises:

Type Description
MissingPackageError

if the requests package is not installed. The message gives the command to install it.

Example
>>> from feu.imports import check_requests
>>> check_requests()  # doctest: +SKIP

feu.imports.optional.check_rich

check_rich() -> None

Check if the rich package is installed.

Raises:

Type Description
MissingPackageError

if the rich package is not installed. The message gives the command to install it.

Example
>>> from feu.imports import check_rich
>>> check_rich()  # doctest: +SKIP

feu.imports.optional.is_click_available

is_click_available() -> bool

Indicate if the click package is installed and can be imported.

Returns:

Type Description
bool

True if click is available otherwise False.

Example
>>> from feu.imports import is_click_available
>>> isinstance(is_click_available(), bool)
True

feu.imports.optional.is_git_available

is_git_available() -> bool

Indicate if the git package is installed and can be imported.

Returns:

Type Description
bool

True if git is available otherwise False.

Example
>>> from feu.imports import is_git_available
>>> isinstance(is_git_available(), bool)
True

feu.imports.optional.is_requests_available

is_requests_available() -> bool

Indicate if the requests package is installed and can be imported.

Returns:

Type Description
bool

True if requests is available otherwise False.

Example
>>> from feu.imports import is_requests_available
>>> isinstance(is_requests_available(), bool)
True

feu.imports.optional.is_rich_available

is_rich_available() -> bool

Indicate if the rich package is installed and can be imported.

Returns:

Type Description
bool

True if rich is available otherwise False.

Example
>>> from feu.imports import is_rich_available
>>> isinstance(is_rich_available(), bool)
True

feu.imports.lazy

Implement a utility function to lazily import the names of a package.

feu.imports.lazy.lazy_exports

lazy_exports(
    package: str,
    exports: Mapping[str, str],
    namespace: dict[str, Any],
) -> tuple[Callable[[str], Any], Callable[[], list[str]]]

Create the __getattr__ and __dir__ of a package that imports some of its names when they are used.

The names are in the __all__ of the package, so from package import name works as usual, but the module that defines a name is imported the first time the name is used. This avoids importing the optional libraries that a module needs when the package is imported.

Parameters:

Name Type Description Default
package str

The name of the package, usually __name__.

required
exports Mapping[str, str]

The module that defines each lazy name.

required
namespace dict[str, Any]

The namespace of the package, usually globals(). A name is added to it when it is imported, so the next access does not call __getattr__.

required

Returns:

Type Description
Callable[[str], Any]

The __getattr__ and __dir__ functions of the package.

Callable[[], list[str]]

The returned __getattr__ raises an AttributeError if the

tuple[Callable[[str], Any], Callable[[], list[str]]]

name is not in exports.

Example
>>> namespace = {}
>>> getattr_, dir_ = lazy_exports("example", {"OrderedDict": "collections"}, namespace)
>>> getattr_("OrderedDict")
<class 'collections.OrderedDict'>
>>> "OrderedDict" in namespace
True