Skip to content

Fix LoadImage to raise OptionalImportError when specified reader is not available #8522

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: dev
Choose a base branch
from

Conversation

its-serah
Copy link

Description

This PR fixes issue #7437 by making LoadImage raise an OptionalImportError when a specified reader is not installed, instead of silently falling back to another reader.

Changes

  • Modified LoadImage.__init__ to catch ValueError from look_up_option when reader name is not recognized
  • Raise OptionalImportError instead of just warning when specified reader is not installed
  • Added test case to verify the new behavior

Why this is needed

Previously, when a user specified LoadImage(reader='ITKReader') without ITK installed, it would just warn and use PILReader instead. This could lead to confusion and unexpected behavior. Now it properly raises an OptionalImportError to make it clear that the requested reader is not available.

Fixes #7437

…ot available

- Modified LoadImage.__init__ to catch ValueError from look_up_option when reader name is not recognized
- Raise OptionalImportError instead of just warning when specified reader is not installed
- Added test case to verify the new behavior

This addresses issue Project-MONAI#7437 where LoadImage would silently fall back to another reader
when the specified reader (e.g., ITKReader) was not installed. Now it properly raises
an OptionalImportError to make it clear that the requested reader is not available.

Fixes: Project-MONAI#7437
Copy link

coderabbitai bot commented Jul 29, 2025

Walkthrough

The changes update error handling in the LoadImage and LoadImaged classes so that specifying a non-existent or uninstalled reader raises an OptionalImportError instead of issuing a warning or falling back to another reader. This is done by adding a raise_on_missing_reader parameter controlling this behavior and wrapping reader lookup in a try-except block. Corresponding tests verify that the exception is raised when expected and that the flag behaves correctly.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~7 minutes

Assessment against linked issues

Objective Addressed Explanation
Raise exception if specified reader in LoadImage is not installed (#7437)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes detected.

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Knowledge Base: Disabled due to Reviews > Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between a741d0b and 2af0501.

📒 Files selected for processing (3)
  • monai/transforms/io/array.py (4 hunks)
  • monai/transforms/io/dictionary.py (3 hunks)
  • tests/transforms/test_load_image.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • monai/transforms/io/array.py
  • tests/transforms/test_load_image.py
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py

⚙️ CodeRabbit Configuration File

Review the Python code for quality and correctness. Ensure variable names adhere to PEP8 style guides, are sensible and informative in regards to their function, though permitting simple names for loop and comprehension variables. Ensure routine names are meaningful in regards to their function and use verbs, adjectives, and nouns in a semantically appropriate way. Docstrings should be present for all definition which describe each variable, return value, and raised exception in the appropriate section of the Google-style of docstrings. Examine code for logical error or inconsistencies, and suggest what may be changed to addressed these. Suggest any enhancements for code improving efficiency, maintainability, comprehensibility, and correctness. Ensure new or modified definitions will be covered by existing or new unit tests.

Files:

  • monai/transforms/io/dictionary.py
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (19)
  • GitHub Check: build-docs
  • GitHub Check: flake8-py3 (codeformat)
  • GitHub Check: flake8-py3 (pytype)
  • GitHub Check: quick-py3 (macOS-latest)
  • GitHub Check: flake8-py3 (mypy)
  • GitHub Check: quick-py3 (windows-latest)
  • GitHub Check: quick-py3 (ubuntu-latest)
  • GitHub Check: packaging
  • GitHub Check: min-dep-py3 (3.12)
  • GitHub Check: min-dep-os (windows-latest)
  • GitHub Check: min-dep-os (ubuntu-latest)
  • GitHub Check: min-dep-os (macOS-latest)
  • GitHub Check: min-dep-pytorch (2.7.1)
  • GitHub Check: min-dep-pytorch (2.6.0)
  • GitHub Check: min-dep-py3 (3.9)
  • GitHub Check: min-dep-py3 (3.10)
  • GitHub Check: min-dep-py3 (3.11)
  • GitHub Check: min-dep-pytorch (2.5.1)
  • GitHub Check: min-dep-pytorch (2.4.1)
🔇 Additional comments (4)
monai/transforms/io/dictionary.py (4)

90-90: Parameter placement and naming are correct.

The raise_on_missing_reader parameter is appropriately positioned after existing parameters and follows Python naming conventions.


127-128: Documentation accurately describes the new parameter.

The docstring clearly explains the parameter's purpose and default behavior for backward compatibility.


142-142: Parameter correctly passed to underlying LoadImage.

The flag is properly forwarded to the internal _loader instance, maintaining consistency between the dictionary wrapper and array transform.


133-145: Parameter order is correct; no action needed.
The LoadImage constructor in array.py defines its parameters in the exact same sequence (reader, image_only, dtype, ensure_channel_first, simple_keys, prune_meta_pattern, prune_meta_sep, expanduser, raise_on_missing_reader, *args, **kwargs), matching the call in dictionary.py.
All good here.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@ericspod
Copy link
Member

ericspod commented Aug 6, 2025

Hi @its-serah thanks for the contribution. As you see from the failed tests the expectation of the reader is to not raise an exception if an optional package isn't found, and this is correct in the cases when a fallback reader does exist for some formats. If we raise an exception whenever a reader can't be loaded then this fallback behaviour can't happen. I would suggest that we add a flag as a member to the class to enable the exception behaviour, but whose default state retains the existing behaviour. We would also need tests to check that turning this on correctly raises exceptions. What do you think? There's interest in the associated issue so I'm keen to find a solution that works for everyone. Thanks!

its-serah and others added 3 commits August 8, 2025 00:12
- Add raise_on_missing_reader parameter (defaults to False for backward compatibility)
- When True, raises OptionalImportError if specified reader is not available
- When False (default), issues warning and uses fallback readers
- Update tests to verify new behavior
- Addresses reviewer feedback on PR Project-MONAI#8522
- Pass through raise_on_missing_reader parameter to underlying LoadImage
- Update docstring to document the new parameter
- Ensure consistent behavior between array and dictionary versions
@its-serah
Copy link
Author

Hi @ericspod thanks for the excellent feedback! I've implemented exactly what you suggested. I added a raise_on_missing_reader flag to both LoadImage and LoadImaged classes that defaults to False to maintain existing behavior and backward compatibility. When set to True, it raises OptionalImportError for missing readers. When False (default), it preserves the current fallback behavior with warnings. I also added comprehensive tests to verify the flag correctly raises exceptions when enabled. This gives users control while maintaining the important fallback functionality for existing codebases. The failed tests should now pass since the default behavior is unchanged. What do you think of this approach?

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
2 participants