Skip to content

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

Added 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

Objective Addressed Explanation
Raise exception if specified reader in LoadImage is not installed (#7437) The change makes this behavior configurable via raise_on_missing_reader, but the default remains False, so the exception is not raised by default.

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 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.
    • 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.
  • 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 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/Issue comments)

Type @coderabbitai help to get the list of available commands.

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.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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!

- 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?

the_reader = look_up_option(_r.lower(), SUPPORTED_READERS)
except ValueError:
# If the reader name is not recognized at all, raise OptionalImportError
raise OptionalImportError(
Copy link
Member

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.

@ericspod
Copy link
Member

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 (./runtests.sh --autofix will do it). Thanks!

…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]>
@its-serah its-serah force-pushed the fix-loadimage-reader-exception branch from 68102c1 to e332430 Compare August 25, 2025 12:03
@its-serah
Copy link
Author

Hi @ericspod thanks for the feedback! I've addressed both issues you mentioned:

Fixed the guarding mechanism: Both raise OptionalImportError statements now use the same raise_on_missing_reader flag mechanism for consistent behavior.

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 raise_on_missing_reader=False, both cases will show warnings and allow fallback behavior. When True, both will raise OptionalImportError.

Copy link

@coderabbitai coderabbitai bot left a 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 raise OptionalImportError 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 types

Please update the LoadImage docstring to document the new behavior and list all supported reader 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 order

Tests 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

📥 Commits

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

📒 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.

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