-
Notifications
You must be signed in to change notification settings - Fork 1.3k
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 Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Assessment against linked issues
Pre-merge checks (3 passed, 2 warnings)❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ 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. Comment |
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.
Hi @its-serah thanks for continuing to work on this, I think it's much better with some minor suggestions. The tests are failing however so please look again and what your tests are testing to see what the issue is. The DCO still doesn't seem happy but we can sort that last and just force it to pass if needed. |
- Refactor duplicate error messaging for missing reader handling as suggested by @ericspod - Extract common error message strings to avoid duplication - Fix test to properly verify raise_on_missing_reader=False behavior - Update test to expect warnings instead of exceptions when flag is disabled - Maintain backward compatibility with proper error handling
- Keep the corrected test implementation that matches the actual behavior - Maintain raise_on_missing_reader=False warning behavior instead of exception
for more information, see https://pre-commit.ci
Hey @ericspod Thank you for the code review feedback! I've addressed both of your suggestions in the latest commits: Refactored duplicate error messaging: Fixed the failing test: The changes maintain backward compatibility while implementing the cleaner code structure you suggested. I've also verified that the functionality works as expected with custom tests. The CI failures should now be resolved since the test logic correctly matches the implementation behavior. Please let me know if you need any clarifications or have additional feedback! |
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: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
tests/transforms/test_load_image.py (1)
14-25
: Importwarnings
to fix NameError in tests.
warnings
is used below but not imported (Ruff F821 at Lines 458–459).Apply:
import os import shutil import tempfile import unittest +import warnings from pathlib import Path
🧹 Nitpick comments (5)
test_my_changes.py (4)
1-1
: Drop the shebang or make the file executable.The shebang triggers EXE001 under lint unless the file is chmod +x. For tests, the shebang is unnecessary—remove it.
Apply:
-#!/usr/bin/env python3
25-33
: Use an assertion and avoid the unused variable warning (F841).Assert the created loader type and keep the variable used.
Apply:
- loader = LoadImage(reader="UnknownReader", raise_on_missing_reader=False) - if w and "UnknownReader" in str(w[0].message): + loader = LoadImage(reader="UnknownReader", raise_on_missing_reader=False) + assert isinstance(loader, LoadImage) + if w and "UnknownReader" in str(w[0].message): print(f"PASS: Got expected warning: {w[0].message}")
43-48
: Fix unused variables (F841) and avoid blindexcept Exception
(BLE001).Don’t assign unused, and narrow the except.
Apply:
- loader1 = LoadImage(reader="PILReader", raise_on_missing_reader=True) - loader2 = LoadImage(reader="PILReader", raise_on_missing_reader=False) + LoadImage(reader="PILReader", raise_on_missing_reader=True) + LoadImage(reader="PILReader", raise_on_missing_reader=False) print("PASS: Both loaders created successfully with valid reader") - except Exception as e: + except OptionalImportError as e: print(f"FAIL: Unexpected error with valid reader: {e}") return False
9-52
: Consider rewriting this as a pytest/unittest test with asserts (optional).Printing “PASS/FAIL” and returning booleans reduces signal in CI. Using asserts/pytest.raises will integrate better with the suite (and remove TRY300).
I can convert this function to pytest-style with proper assertions if you want.
tests/transforms/test_load_image.py (1)
456-464
: Robustness: assert warning content with full message or regex.Message text now includes a follow-up sentence; using substring match is fine, but consider
assertWarnsRegex
or stricter predicate. Also depends on warnings stacklevel in the implementation (addressed below).
📜 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 (3)
monai/transforms/io/array.py
(4 hunks)test_my_changes.py
(1 hunks)tests/transforms/test_load_image.py
(2 hunks)
🧰 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:
test_my_changes.py
monai/transforms/io/array.py
tests/transforms/test_load_image.py
🪛 Ruff (0.12.2)
test_my_changes.py
1-1: Shebang is present but file is not executable
(EXE001)
18-18: Consider moving this statement to an else
block
(TRY300)
27-27: Local variable loader
is assigned to but never used
Remove assignment to unused variable loader
(F841)
36-36: Do not catch blind exception: Exception
(BLE001)
43-43: Local variable loader1
is assigned to but never used
Remove assignment to unused variable loader1
(F841)
44-44: Local variable loader2
is assigned to but never used
Remove assignment to unused variable loader2
(F841)
46-46: Do not catch blind exception: Exception
(BLE001)
monai/transforms/io/array.py
219-219: Within an except
clause, raise exceptions with raise ... from err
or raise ... from None
to distinguish them from errors in exception handling
(B904)
221-221: No explicit stacklevel
keyword argument found
Set stacklevel=2
(B028)
230-230: No explicit stacklevel
keyword argument found
Set stacklevel=2
(B028)
tests/transforms/test_load_image.py
458-458: Undefined name warnings
(F821)
459-459: Undefined name warnings
(F821)
⏰ 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). (13)
- GitHub Check: min-dep-pytorch (2.6.0)
- GitHub Check: min-dep-os (ubuntu-latest)
- GitHub Check: min-dep-os (macOS-latest)
- GitHub Check: min-dep-os (windows-latest)
- GitHub Check: min-dep-pytorch (2.7.1)
- GitHub Check: min-dep-pytorch (2.8.0)
- GitHub Check: min-dep-pytorch (2.5.1)
- GitHub Check: min-dep-py3 (3.9)
- GitHub Check: min-dep-py3 (3.10)
- GitHub Check: quick-py3 (ubuntu-latest)
- GitHub Check: quick-py3 (macOS-latest)
- GitHub Check: packaging
- GitHub Check: quick-py3 (windows-latest)
🔇 Additional comments (2)
tests/transforms/test_load_image.py (1)
440-444
: Align test with new default behavior
Defaultraise_on_missing_reader=False
; either passraise_on_missing_reader=True
in this test or rewrite it to assert the warning-and-fallback path instead of expecting an exception. Manual check ofLoadImage
’s signature and defaults required.monai/transforms/io/array.py (1)
141-167
: Docstring/API LGTM.New
raise_on_missing_reader
parameter is documented clearly; default preserves backward compatibility.
try: | ||
the_reader = look_up_option(_r.lower(), SUPPORTED_READERS) | ||
except ValueError: | ||
# If the reader name is not recognized at all, raise OptionalImportError | ||
msg = f"Cannot find reader '{_r}'. It may not be installed or recognized." | ||
if self.raise_on_missing_reader: | ||
raise OptionalImportError(msg) | ||
else: | ||
warnings.warn(f"{msg} Will use fallback readers if available.") | ||
continue | ||
try: |
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.
🛠️ Refactor suggestion
Chain the original cause and set stacklevel
on warnings.
Use raise ... from err
(B904) and add stacklevel=2
so warnings point at user code (B028).
Apply:
- if the_reader is None:
- try:
- the_reader = look_up_option(_r.lower(), SUPPORTED_READERS)
- except ValueError:
+ if the_reader is None:
+ try:
+ the_reader = look_up_option(_r.lower(), SUPPORTED_READERS)
+ except ValueError as err:
# If the reader name is not recognized at all, raise OptionalImportError
msg = f"Cannot find reader '{_r}'. It may not be installed or recognized."
if self.raise_on_missing_reader:
- raise OptionalImportError(msg)
+ raise OptionalImportError(msg) from err
else:
- warnings.warn(f"{msg} Will use fallback readers if available.")
+ warnings.warn(f"{msg} Will use fallback readers if available.", stacklevel=2)
continue
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
try: | |
the_reader = look_up_option(_r.lower(), SUPPORTED_READERS) | |
except ValueError: | |
# If the reader name is not recognized at all, raise OptionalImportError | |
msg = f"Cannot find reader '{_r}'. It may not be installed or recognized." | |
if self.raise_on_missing_reader: | |
raise OptionalImportError(msg) | |
else: | |
warnings.warn(f"{msg} Will use fallback readers if available.") | |
continue | |
try: | |
if the_reader is None: | |
try: | |
the_reader = look_up_option(_r.lower(), SUPPORTED_READERS) | |
except ValueError as err: | |
# If the reader name is not recognized at all, raise OptionalImportError | |
msg = f"Cannot find reader '{_r}'. It may not be installed or recognized." | |
if self.raise_on_missing_reader: | |
raise OptionalImportError(msg) from err | |
else: | |
warnings.warn(f"{msg} Will use fallback readers if available.", stacklevel=2) | |
continue | |
try: |
🧰 Tools
🪛 Ruff (0.12.2)
219-219: Within an except
clause, raise exceptions with raise ... from err
or raise ... from None
to distinguish them from errors in exception handling
(B904)
221-221: No explicit stacklevel
keyword argument found
Set stacklevel=2
(B028)
🤖 Prompt for AI Agents
In monai/transforms/io/array.py around lines 213 to 223, the except block
swallows the original ValueError and issues warnings without stacklevel; change
the except to "except ValueError as err:" then when raising OptionalImportError
use "raise OptionalImportError(msg) from err" to chain the original cause, and
when issuing the warning call warnings.warn(f"{msg} Will use fallback readers if
available.", stacklevel=2) so the warning points at user code.
except OptionalImportError as e: | ||
msg = f"Required package for reader {_r} is not installed, or the version doesn't match requirement." | ||
if self.raise_on_missing_reader: | ||
raise OptionalImportError(msg) from e | ||
else: | ||
warnings.warn(f"{msg} Will use fallback readers if available.") | ||
except TypeError: # the reader doesn't have the corresponding args/kwargs | ||
warnings.warn(f"{_r} is not supported with the given parameters {args} {kwargs}.") | ||
self.register(the_reader()) |
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.
🛠️ Refactor suggestion
Also set stacklevel
for dependency-missing warnings.
Keep the raised error chained; just add stacklevel=2
for the warning path.
Apply:
except OptionalImportError as e:
msg = f"Required package for reader {_r} is not installed, or the version doesn't match requirement."
if self.raise_on_missing_reader:
raise OptionalImportError(msg) from e
else:
- warnings.warn(f"{msg} Will use fallback readers if available.")
+ warnings.warn(f"{msg} Will use fallback readers if available.", stacklevel=2)
except TypeError: # the reader doesn't have the corresponding args/kwargs
- warnings.warn(f"{_r} is not supported with the given parameters {args} {kwargs}.")
+ warnings.warn(f"{_r} is not supported with the given parameters {args} {kwargs}.", stacklevel=2)
self.register(the_reader())
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
except OptionalImportError as e: | |
msg = f"Required package for reader {_r} is not installed, or the version doesn't match requirement." | |
if self.raise_on_missing_reader: | |
raise OptionalImportError(msg) from e | |
else: | |
warnings.warn(f"{msg} Will use fallback readers if available.") | |
except TypeError: # the reader doesn't have the corresponding args/kwargs | |
warnings.warn(f"{_r} is not supported with the given parameters {args} {kwargs}.") | |
self.register(the_reader()) | |
except OptionalImportError as e: | |
msg = f"Required package for reader {_r} is not installed, or the version doesn't match requirement." | |
if self.raise_on_missing_reader: | |
raise OptionalImportError(msg) from e | |
else: | |
warnings.warn(f"{msg} Will use fallback readers if available.", stacklevel=2) | |
except TypeError: # the reader doesn't have the corresponding args/kwargs | |
warnings.warn(f"{_r} is not supported with the given parameters {args} {kwargs}.", stacklevel=2) | |
self.register(the_reader()) |
🧰 Tools
🪛 Ruff (0.12.2)
230-230: No explicit stacklevel
keyword argument found
Set stacklevel=2
(B028)
232-232: No explicit stacklevel
keyword argument found
Set stacklevel=2
(B028)
🤖 Prompt for AI Agents
In monai/transforms/io/array.py around lines 225 to 233, the OptionalImportError
except block currently warns when readers are missing but does not set
stacklevel; keep the existing chained raise as-is, and update the warning path
to include stacklevel=2 so the warning points to the caller (i.e., call
warnings.warn(message, stacklevel=2)). Do not change the raised error chaining;
only add the stacklevel=2 argument to the warnings.warn call in the else branch.
except Exception as e: | ||
print(f"FAIL: Unexpected error: {e}") | ||
return False |
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.
🛠️ Refactor suggestion
Remove the blind except Exception
(BLE001).
Catching all exceptions hides real failures; let unexpected errors surface.
Apply:
- except Exception as e:
- print(f"FAIL: Unexpected error: {e}")
- return False
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
except Exception as e: | |
print(f"FAIL: Unexpected error: {e}") | |
return False |
🧰 Tools
🪛 Ruff (0.12.2)
36-36: Do not catch blind exception: Exception
(BLE001)
🤖 Prompt for AI Agents
In test_my_changes.py around lines 36 to 38, the code currently uses a blind
except Exception which hides unexpected failures; replace it by either removing
the try/except so exceptions propagate, or catch only the specific exception
types you expect (e.g., ValueError, AssertionError) and handle those, and for
any other exception re-raise it (or omit handling) so test runners see real
errors; update logging to record expected exception details only and ensure
unexpected exceptions are not swallowed.
Hi @its-serah thanks for the update, I think this addresses the suggested code I had. The tests are failing however since your tests are attempting to load a non-existent file. There's also a few things from Coderabbit but we're just about there. |
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