|
14 | 14 | is_tiled_image, |
15 | 15 | ) |
16 | 16 |
|
17 | | -from importlib import import_module |
| 17 | +from importlib import import_module, metadata |
| 18 | +from packaging.requirements import Requirement |
18 | 19 | from types import ModuleType |
19 | | -from typing import Optional |
20 | 20 |
|
21 | 21 | # Several functions that were initially defined in this module were moved to |
22 | 22 | # highdicom.spatial to consolidate similar functionality and prevent circular |
@@ -275,21 +275,33 @@ def import_optional_dependency( |
275 | 275 | ImportError |
276 | 276 | When the specified module cannot be imported. |
277 | 277 | """ |
| 278 | + for req_str in metadata.requires('highdicom'): |
| 279 | + req = Requirement(req_str) |
| 280 | + if req.name == module_name: |
| 281 | + break |
278 | 282 |
|
279 | | - #Update as new optional dependencies are supported |
280 | | - versions = {} |
| 283 | + else: |
| 284 | + raise ValueError( |
| 285 | + f'`{module_name}` is not a requirement of highdicom' |
| 286 | + f' but is required for {feature}.' |
| 287 | + ) |
281 | 288 |
|
282 | 289 | try: |
283 | | - return import_module(name=module_name) |
| 290 | + module = import_module(name=module_name) |
| 291 | + installed_version = metadata.version(module_name) |
284 | 292 |
|
285 | | - except ImportError as error: |
286 | | - module_version = ( |
287 | | - versions[module_name] if module_name in versions.keys() else 'Unknown' |
288 | | - ) |
| 293 | + if installed_version not in req.specifier: |
| 294 | + raise ImportError( |
| 295 | + f'Optional dependency `{module_name}` has an unsuitable' |
| 296 | + f' version. Found {installed_version}, but highdicom requires' |
| 297 | + f' {module_name}{req.specifier}.' |
| 298 | + ) |
289 | 299 |
|
| 300 | + return module |
| 301 | + |
| 302 | + except ImportError as error: |
290 | 303 | raise ImportError( |
291 | 304 | f'Optional dependency `{module_name}` could not be imported' |
292 | | - + (f' but is required for {feature}.' if feature else '.') |
293 | | - + f' The minimum required version for `{module_name}` is {module_version}.' |
294 | | - |
| 305 | + f' but is required for {feature}.' |
| 306 | + f' highdicom requires {module_name}{req.specifier}.' |
295 | 307 | ) from error |
0 commit comments