-
Notifications
You must be signed in to change notification settings - Fork 1.2k
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
base: dev
Are you sure you want to change the base?
Fix LoadImage to raise OptionalImportError when specified reader is not available #8522
Conversation
…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
WalkthroughAdded a new boolean parameter raise_on_missing_reader to LoadImage and propagated it to LoadImaged. LoadImage now wraps reader name lookup and reader registration in try/except handling that will raise OptionalImportError when raise_on_missing_reader is True; otherwise it emits warnings and continues to fallback readers. Two tests were added to verify behavior when a reader is not available and the raise_on_missing_reader flag behavior. Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Assessment against linked issues
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. ✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
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! |
- 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
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? |
monai/transforms/io/array.py
Outdated
the_reader = look_up_option(_r.lower(), SUPPORTED_READERS) | ||
except ValueError: | ||
# If the reader name is not recognized at all, raise OptionalImportError | ||
raise OptionalImportError( |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think we need if self.raise_on_missing_reader
here as well.
Hi @its-serah it looks better now, but I think the two raises need to be guarded by the same mechanism. Other than that it looks good though you'll have to fix your DCO issue and the formatting issue ( |
…r flag Both raise statements in LoadImage.__init__ now use the same guarding mechanism via the raise_on_missing_reader flag. This ensures consistent behavior when dealing with missing readers whether they are unrecognized names or missing optional dependencies. Also applied code formatting fixes. Signed-off-by: Sarah <[email protected]>
68102c1
to
e332430
Compare
for more information, see https://pre-commit.ci
Hi @ericspod thanks for the feedback! I've addressed both issues you mentioned: Fixed the guarding mechanism: Both Fixed DCO and formatting: Added proper DCO sign-off and applied code formatting fixes using isort, black, and ruff. The changes ensure that both exception cases (unrecognized reader name and missing dependencies) are handled consistently through the same flag. When |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
♻️ Duplicate comments (1)
monai/transforms/io/array.py (1)
243-245
: Class-specified reader path bypasses the flag — instantiation may raise unguarded.If users pass a reader class (e.g.,
LoadImage(reader=ITKReader, raise_on_missing_reader=False)
), instantiation will raiseOptionalImportError
unconditionally, ignoring the new flag. Guard this path like the string-based path.- elif inspect.isclass(_r): - self.register(_r(*args, **kwargs)) + elif inspect.isclass(_r): + try: + self.register(_r(*args, **kwargs)) + except OptionalImportError as e: + if self.raise_on_missing_reader: + raise OptionalImportError( + f"required package for reader {_r.__name__} is not installed, or the version doesn't match requirement." + ) from e + else: + warnings.warn( + f"required package for reader {_r.__name__} is not installed, or the version doesn't match requirement. " + f"Will use fallback readers if available.", + category=UserWarning, + stacklevel=2, + ) + except TypeError: + warnings.warn( + f"{_r.__name__} is not supported with the given parameters {args} {kwargs}.", + category=UserWarning, + stacklevel=2, + ) + self.register(_r())
🧹 Nitpick comments (3)
monai/transforms/io/array.py (3)
213-226
: Unknown reader name handling: enrich warnings and callsite context.Behavior is correct. Improve usability by adding
stacklevel
and explicit category so the warning points callers to their site.- else: - warnings.warn( - f"Cannot find reader '{_r}'. It may not be installed or recognized. " - f"Will use fallback readers if available." - ) + else: + warnings.warn( + f"Cannot find reader '{_r}'. It may not be installed or recognized. " + f"Will use fallback readers if available.", + category=UserWarning, + stacklevel=2, + )
229-238
: Missing optional dependency: add stacklevel/category to warning.Same UX improvement as above; keep messages actionable at the callsite.
- else: - warnings.warn( - f"required package for reader {_r} is not installed, or the version doesn't match requirement. " - f"Will use fallback readers if available." - ) + else: + warnings.warn( + f"required package for reader {_r} is not installed, or the version doesn't match requirement. " + f"Will use fallback readers if available.", + category=UserWarning, + stacklevel=2, + )
165-167
: Docstring: add Raises section and clarify accepted reader typesPlease update the
LoadImage
docstring to document the new behavior and list all supportedreader
formats. For example:- raise_on_missing_reader: if True, raise OptionalImportError when a specified reader is not available, - otherwise attempt to use fallback readers. Default is False to maintain backward compatibility. - args: additional parameters for reader if providing a reader name. + raise_on_missing_reader: if True, raise `OptionalImportError` when a specified reader is not available; + otherwise attempt to use fallback readers. Defaults to False (backward compatibility). + args: additional parameters for reader if providing a reader name. + + Raises: + OptionalImportError: If `raise_on_missing_reader=True` and the specified reader cannot be + found or its optional dependency is not installed. + + Accepted reader types: + - str: name of a registered reader (e.g., `"ITKReader"`) + - class: e.g., `ITKReader` or a custom reader class + - instance: e.g., `ITKReader(pixel_type=itk.UC)` + - list/tuple: multiple reader names or classes to try in orderTests already cover:
- string reader with
raise_on_missing_reader=True/False
- custom reader class and instance
- default behavior for class readers
For completeness, you may optionally add a test that passes a reader class with
raise_on_missing_reader=True
to confirm it still succeeds (no exception).
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Knowledge Base: Disabled due to Reviews > Disable Knowledge Base setting
📒 Files selected for processing (2)
monai/transforms/io/array.py
(4 hunks)tests/transforms/test_load_image.py
(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- 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/array.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: quick-py3 (ubuntu-latest)
- GitHub Check: packaging
- GitHub Check: build-docs
- GitHub Check: quick-py3 (macOS-latest)
- GitHub Check: flake8-py3 (codeformat)
- GitHub Check: flake8-py3 (mypy)
- GitHub Check: quick-py3 (windows-latest)
- GitHub Check: flake8-py3 (pytype)
- GitHub Check: min-dep-pytorch (2.6.0)
- GitHub Check: min-dep-pytorch (2.8.0)
- GitHub Check: min-dep-pytorch (2.7.1)
- GitHub Check: min-dep-py3 (3.11)
- GitHub Check: min-dep-pytorch (2.5.1)
- GitHub Check: min-dep-py3 (3.9)
- GitHub Check: min-dep-os (windows-latest)
- GitHub Check: min-dep-py3 (3.12)
- GitHub Check: min-dep-os (ubuntu-latest)
- GitHub Check: min-dep-py3 (3.10)
- GitHub Check: min-dep-os (macOS-latest)
🔇 Additional comments (1)
monai/transforms/io/array.py (1)
141-144
: Opt-in flag preserves back-compat — good addition.Adding
raise_on_missing_reader: bool = False
is the right trade-off to surface explicit failures without breaking existing flows.
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
LoadImage.__init__
to catch ValueError fromlook_up_option
when reader name is not recognizedOptionalImportError
instead of just warning when specified reader is not installedWhy 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