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

torchio.external.imports   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 27
dl 0
loc 44
rs 10
c 0
b 0
f 0
wmc 9

6 Functions

Rating   Name   Duplication   Size   Complexity  
A get_pandas() 0 2 1
A get_ffmpeg() 0 4 1
A _check_module() 0 9 3
A _check_executable() 0 7 2
A get_distinctipy() 0 2 1
A _check_and_import() 0 3 1
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