Passed
Pull Request — main (#1346)
by Fernando
01:33
created

torchio.external.imports.get_pandas()   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nop 0
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
from importlib import import_module
2
from importlib.util import find_spec
3
from shutil import which
4
from types import ModuleType
5
6
7
def _check_module(*, module: str, extra: str, package: str | None = None) -> None:
8
    if find_spec(module) is None:
9
        name = module if package is None else package
10
        message = (
11
            f'The `{name}` package is required for this.'
12
            f' Install TorchIO with the `{extra}` extra:'
13
            f' `pip install torchio[{extra}]`.'
14
        )
15
        raise ImportError(message)
16
17
18
def _check_and_import(module: str, extra: str, **kwargs) -> ModuleType:
19
    _check_module(module=module, extra=extra, **kwargs)
20
    return import_module(module)
21
22
23
def get_pandas() -> ModuleType:
24
    return _check_and_import(module='pandas', extra='csv')
25
26
27
def get_distinctipy() -> ModuleType:
28
    return _check_and_import(module='distinctipy', extra='plot')
29
30
31
def get_ffmpeg() -> ModuleType:
32
    ffmpeg = _check_and_import(module='ffmpeg', extra='video', package='ffmpeg-python')
33
    _check_executable('ffmpeg')
34
    return ffmpeg
35
36
37
def _check_executable(executable: str) -> None:
38
    if which(executable) is None:
39
        message = (
40
            f'The `{executable}` executable is required for this. Install it from your'
41
            ' package manager or download it from the official website.'
42
        )
43
        raise FileNotFoundError(message)
44