Skip to content

Raise exception when user-specified reader package is not installed#8771

Open
haoyu-haoyu wants to merge 1 commit intoProject-MONAI:devfrom
haoyu-haoyu:fix/raise-exception-when-specified-reader-not-installed
Open

Raise exception when user-specified reader package is not installed#8771
haoyu-haoyu wants to merge 1 commit intoProject-MONAI:devfrom
haoyu-haoyu:fix/raise-exception-when-specified-reader-not-installed

Conversation

@haoyu-haoyu
Copy link

Fixes #7437

Description

When a user explicitly specifies a reader (e.g., reader="ITKReader") but the required package is not installed, LoadImage now raises an OptionalImportError instead of silently falling back to another reader with only a warning.

Before (current behavior):

# User specifies ITKReader but itk is not installed
loader = LoadImage(reader="ITKReader")
# Only a warning is printed, then PILReader is used silently
# This can lead to unexpected results

After (new behavior):

# User specifies ITKReader but itk is not installed
loader = LoadImage(reader="ITKReader")
# OptionalImportError is raised immediately with a clear message:
# "Required package for reader ITKReader is not installed..."

Default behavior (reader=None) remains unchanged — missing optional packages are still handled gracefully with debug logging, and the system falls back to available readers as before.

Changes

  1. monai/transforms/io/array.py: Changed warnings.warn() to raise OptionalImportError() in the user-specified reader registration path (lines 212-216).

  2. tests/transforms/test_load_image.py: Added TestLoadImageReaderNotInstalled test class with:

    • test_specified_reader_not_installed_raises: Direct test (runs when itk is NOT installed)
    • test_specified_reader_not_installed_raises_mocked: Mock-based test that always runs, simulating a reader whose package is not installed

Testing

  • New unit tests added
  • Existing tests unaffected (default reader=None path unchanged)

Signed-off-by: haoyu-haoyu haoyu-haoyu@users.noreply.github.com

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Raise the exception when LoadImage has a reader specified but it is not installed

1 participant