-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Replace pyupgrade with builtin Ruff's UP rule
#8606
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?
Conversation
|
Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. 📝 WalkthroughWalkthroughThis PR updates typing and formatting across many files: replaces typing.Union/Optional and typing container aliases with Python 3.10+ Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Cache: Disabled due to data retention organization setting Knowledge base: Disabled due to 📒 Files selected for processing (1)
🧰 Additional context used📓 Path-based instructions (1)**/*.py⚙️ CodeRabbit configuration file
Files:
⏰ 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). (18)
🔇 Additional comments (3)
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 |
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.
Greptile Overview
Greptile Summary
This PR modernizes Python syntax across five files by replacing outdated string formatting methods (.format()) with f-strings and updating lru_cache(maxsize=None) to the modern cache decorator. The changes align with Ruff's UP (pyupgrade) rule, consolidating linting tools to reduce tooling complexity while maintaining code quality. All modifications are syntactically equivalent transformations that adopt Python 3.6+ (f-strings) and Python 3.9+ (cache) best practices. The affected files span profiling utilities, TensorBoard/stats handlers, metrics utilities, and deepgrow datasets—all converting legacy string formatting to the recommended f-string syntax without altering any logic or output.
Important Files Changed
| Filename | Score | Overview |
|---|---|---|
| tests/profile_subclass/profiling.py | 5/5 | Replaced .format() with f-string in a single print statement for profiling output |
| monai/handlers/tensorboard_handlers.py | 5/5 | Converted two warning messages from .format() to f-strings in TensorBoardStatsHandler |
| monai/handlers/stats_handler.py | 5/5 | Modernized two warning messages by replacing .format() with f-strings |
| monai/metrics/utils.py | 5/5 | Replaced lru_cache(maxsize=None) with cache decorator and updated import |
| monai/apps/deepgrow/dataset.py | 5/5 | Converted two logging.info statements from .format() to f-strings |
Confidence score: 5/5
- This PR is safe to merge with minimal risk—all changes are non-breaking syntax modernizations with identical functional behavior.
- Score reflects straightforward string formatting upgrades and standard library improvements that are well-established Python best practices with no logic changes or potential runtime issues.
- No files require special attention—all transformations are syntactically equivalent and maintain identical output.
5 files reviewed, 2 comments
Signed-off-by: jirka <[email protected]>
for more information, see https://pre-commit.ci Signed-off-by: jirka <[email protected]>
Signed-off-by: jirka <[email protected]>
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.
Greptile Overview
Greptile Summary
This review covers only the changes made since the last review, not the entire PR. Since the previous reviews, two critical issues were introduced: a fatal syntax error in monai/losses/dice.py (missing closing quote) that will break imports, and semantically incorrect type hints in monai/losses/sure_loss.py (parameters typed as | None but using non-None sentinel defaults). Additionally, a logical inconsistency exists in monai/losses/perceptual.py where an error message says "Adversarial Loss" instead of "Perceptual Loss" (pre-existing but now more visible). The remaining changes continue the PR's goal of replacing pyupgrade with Ruff's UP rules by modernizing string formatting (.format() → f-strings) and type annotations (Union[X, Y] → X | Y, Optional[X] → X | None, lru_cache(maxsize=None) → cache). These syntactic updates are safe and maintain backward compatibility via from __future__ import annotations already present throughout the codebase.
Important Files Changed
| Filename | Score | Overview |
|---|---|---|
| monai/losses/dice.py | 1/5 | BREAKING: Missing closing quote in f-string causes syntax error on line 497 |
| monai/losses/sure_loss.py | 2/5 | Incorrect type hints: eps and complex_input typed as | None but use non-None sentinel defaults |
| monai/losses/perceptual.py | 4/5 | String formatting updated but error message incorrectly says "Adversarial Loss" instead of "Perceptual Loss" |
| monai/handlers/tensorboard_handlers.py | 4/5 | Format string conversion loses space separator on line 260 (: becomes :) |
| monai/losses/ds_loss.py | 5/5 | Modernizes Union to pipe syntax; safe with postponed annotations |
| monai/losses/spatial_mask.py | 5/5 | Replaces Optional with PEP 604 syntax; functionally equivalent |
| monai/losses/focal_loss.py | 5/5 | Converts Optional to pipe syntax across four type annotations |
| monai/losses/adversarial_loss.py | 5/5 | Updates %-formatting to .format() in error message |
| monai/transforms/utility/array.py | 5/5 | Removes Union import and uses pipe syntax in two method signatures |
| monai/metrics/utils.py | 5/5 | Replaces lru_cache(maxsize=None) with Python 3.9+ cache decorator |
| monai/handlers/stats_handler.py | 5/5 | Converts two .format() calls to f-strings in warning messages |
| monai/apps/deepgrow/dataset.py | 5/5 | Updates logging statements to use f-strings instead of .format() |
| tests/profile_subclass/profiling.py | 5/5 | Replaces .format() with f-string in print statement |
Confidence score: 0/5
- This PR introduces a syntax error that will prevent the module from importing and break production code immediately.
- Score is 0/5 due to the fatal syntax error in
monai/losses/dice.py(missing quote) and semantically incorrect type hints inmonai/losses/sure_loss.pythat misrepresent the parameter contracts. Additional concerns include a copy-paste error inmonai/losses/perceptual.pyand a formatting inconsistency inmonai/handlers/tensorboard_handlers.py. - Critical attention required for
monai/losses/dice.py(line 497),monai/losses/sure_loss.py(lines 46-48, 153),monai/losses/perceptual.py(line 98), andmonai/handlers/tensorboard_handlers.py(line 260).
Additional Comments (1)
-
monai/apps/nnunet/nnunet_bundle.py, line 508-509 (link)style: Type annotations now use PEP 604 syntax but are redundant here since the string literals already enforce types. The
: strcan be removed from both lines
14 files reviewed, 8 comments
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.
Greptile Overview
Greptile Summary
This PR consolidates Python linting by replacing the standalone pyupgrade pre-commit hook with Ruff's built-in UP (pyupgrade) rules. The changes modernize Python syntax across the codebase: type hints are converted from typing.Union[A, B] and typing.Optional[T] to PEP 604 pipe-union syntax (A | B, T | None), .format() and % string formatting are replaced with f-strings, and functools.lru_cache(maxsize=None) is replaced with functools.cache. The .pre-commit-config.yaml removes the pyupgrade hook entirely and moves its exclusion patterns to the ruff hook, while pyproject.toml adds the UP rule to Ruff's lint selection. This architectural change reduces external dependencies, improves linting consistency, and simplifies CI/CD by unifying multiple syntax-modernization checks into a single tool.
Important Files Changed
| Filename | Score | Overview |
|---|---|---|
.pre-commit-config.yaml |
5/5 | Removes standalone pyupgrade hook and consolidates exclusions under ruff |
pyproject.toml |
5/5 | Adds Ruff's UP rule to lint selection, enabling built-in pyupgrade checks |
monai/losses/dice.py |
0/5 | String formatting update introduces syntax error (unclosed quote in error message) |
monai/losses/perceptual.py |
0/5 | String formatting update plus critical indexing bug (off-by-one in feature slice) |
tests/profile_subclass/profiling.py |
1/5 | F-string split across lines will truncate output (missing concatenation) |
monai/losses/sure_loss.py |
2/5 | Type hint conversions introduce incorrect None annotations for sentinel-value parameters |
monai/metrics/utils.py |
3/5 | Replaces lru_cache(maxsize=None) with cache, but function takes mutable default device=None |
monai/handlers/stats_handler.py |
3/5 | F-string replacements missing spacing in warning messages |
monai/handlers/tensorboard_handlers.py |
4/5 | F-string replacements missing spacing in warning messages |
monai/losses/focal_loss.py |
4/5 | Type hints modernized to `T |
monai/apps/deepgrow/dataset.py |
4.5/5 | Logging statements converted to multi-line f-strings correctly |
monai/losses/adversarial_loss.py |
5/5 | String formatting updated from % to .format() correctly |
monai/losses/ds_loss.py |
5/5 | Type hints modernized to PEP 604 union syntax correctly |
monai/losses/spatial_mask.py |
5/5 | Type hints modernized to `T |
monai/transforms/utility/array.py |
5/5 | Type hints modernized from Union to pipe-union syntax correctly |
monai/apps/nnunet/nnunet_bundle.py |
5/5 | Type hints modernized across all function signatures correctly |
Confidence score: 0/5
- This PR is NOT safe to merge due to critical syntax errors and logic bugs that will break production code immediately.
- Score reflects three blocking issues: unclosed string quote in
dice.py(syntax error), off-by-one indexing bug inperceptual.py(incorrect computation), and broken output formatting inprofiling.py(missing string concatenation). Additionally, incorrect type hints insure_loss.pywill mislead type checkers and several f-string replacements introduce minor spacing issues in warning messages. - Pay close attention to
monai/losses/dice.py(syntax error on line497),monai/losses/perceptual.py(indexing bug on line 260 and copy-paste error on line 98),tests/profile_subclass/profiling.py(split f-string on lines 66-67), andmonai/losses/sure_loss.py(incorrect type hints forepsandcomplex_input).
Additional Comments (1)
-
monai/losses/perceptual.py, line 260 (link)logic: off-by-one slicing error: should be
l_idx:r_idxnotl_idx:i+r_idx. This will cause incorrect channel-wise feature indexing.
16 files reviewed, 5 comments
|
|
||
|
|
||
| @lru_cache(maxsize=None) | ||
| @cache |
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.
logic: The decorator @cache does not accept any arguments, so the parameter device=None is not being cached as part of the key. This means calls with different devices will return the same cached tensor on the wrong device, causing errors. Either use @lru_cache(maxsize=None) with a hashable device wrapper, or accept that the cache is device-agnostic and convert the result after retrieval. Should the cache be keyed by device, or is it acceptable to convert the cached tensor to the requested device after retrieval?
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 this is a valid complaint that should be looked at.
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> Signed-off-by: Jirka Borovec <[email protected]>
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.
Greptile Overview
Greptile Summary
This review covers only the changes made since the last review, not the entire PR. The developer has corrected a critical syntax error in monai/losses/dice.py that was identified in the previous review. The error was a missing closing quote in an error message string within the GeneralizedWassersteinDiceLoss class constructor. This fix addresses a SyntaxError that would have prevented the entire monai.losses.dice module from being imported. The correction changes the malformed string 'GDL to the properly quoted 'GDL', ensuring the error message displays correctly when invalid weighting_mode values are provided. This change is part of the broader PR goal to migrate linting from pyupgrade to Ruff's UP rule, which caught this pre-existing syntax error during the linting process.
Important Files Changed
| Filename | Score | Overview |
|---|---|---|
| monai/losses/dice.py | 5/5 | Fixed missing closing quote in error message string on line 497 |
Confidence score: 5/5
- This change is a straightforward syntax error fix with zero risk of unintended side effects
- The fix correctly addresses the exact issue identified in the previous review by properly closing the quoted string
- No files require special attention as the single-line fix is trivial and clearly correct
1 file reviewed, no comments
|
Hi @Borda thanks for the contribution. There's a lot of changes related to typing and f-strings rather than the PyUpgrade change, these are fine but it obscures what is being done here. What is the purpose of changing the |
Good call, but f-string is to be upgraded, and if original pyupgrade mised it, it is rather its issue than Ruff's doing its job, right?
removing
Yes, will do |
Signed-off-by: Jirka Borovec <[email protected]>
Signed-off-by: Jirka Borovec <[email protected]>
Signed-off-by: Jirka Borovec <[email protected]>
Signed-off-by: Jirka Borovec <[email protected]>
Signed-off-by: Jirka Borovec <[email protected]>
Signed-off-by: Jirka Borovec <[email protected]>
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)
monai/networks/nets/vista3d.py (1)
882-882: Fix torch.torch.Tensor typo throughout PositionEmbeddingRandom.
torch.torch.Tensoris invalid - should betorch.Tensor. This typo appears in:
_pe_encodingsignature (line 882)forwardreturn type (line 894)forward_with_coordssignature and return type (lines 910-911)- def _pe_encoding(self, coords: torch.torch.Tensor) -> torch.torch.Tensor: + def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor: - def forward(self, size: tuple[int, int, int]) -> torch.torch.Tensor: + def forward(self, size: tuple[int, int, int]) -> torch.Tensor: def forward_with_coords( - self, coords_input: torch.torch.Tensor, image_size: tuple[int, int, int] - ) -> torch.torch.Tensor: + self, coords_input: torch.Tensor, image_size: tuple[int, int, int] + ) -> torch.Tensor:Also applies to: 894-894, 910-911
🧹 Nitpick comments (4)
monai/networks/nets/spade_network.py (2)
159-159: F-string conversion looks good.The error message is clearer with f-string formatting. Static analysis suggests extracting long messages to the exception class, but this is a minor style preference that can be deferred.
258-258: F-string conversion looks good.Same improvement as line 159. The TRY003 hint (extract long messages to exception class) applies here too but is optional.
monai/networks/blocks/pos_embed_utils.py (2)
45-48: Docstrings use capitalizedListinstead oflist.Lines 45 and 48 reference
List[int]andList[float]but the signature uses lowercaselist. Update for consistency.- grid_size (int | List[int]): The size of the grid in each spatial dimension. + grid_size (int | list[int]): The size of the grid in each spatial dimension. embed_dim (int): The dimension of the embedding. spatial_dims (int): The number of spatial dimensions (2 for 2D, 3 for 3D). - scales (float | List[float]): The scale for every spatial dimension. If a single float is provided, + scales (float | list[float]): The scale for every spatial dimension. If a single float is provided,
95-95: Docstring uses capitalizedListinstead oflist.Line 95 references
List[int]but the signature uses lowercaselist. Update for consistency.- grid_size (List[int]): The size of the grid in each spatial dimension. + grid_size (int | list[int]): The size of the grid in each spatial dimension.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting
📒 Files selected for processing (32)
.pre-commit-config.yaml(1 hunks)monai/apps/detection/utils/anchor_utils.py(3 hunks)monai/networks/blocks/attention_utils.py(1 hunks)monai/networks/blocks/crossattention.py(2 hunks)monai/networks/blocks/denseblock.py(1 hunks)monai/networks/blocks/mlp.py(1 hunks)monai/networks/blocks/patchembedding.py(1 hunks)monai/networks/blocks/pos_embed_utils.py(2 hunks)monai/networks/blocks/rel_pos_embedding.py(2 hunks)monai/networks/blocks/selfattention.py(3 hunks)monai/networks/blocks/spatialattention.py(1 hunks)monai/networks/blocks/transformerblock.py(1 hunks)monai/networks/layers/simplelayers.py(1 hunks)monai/networks/layers/utils.py(1 hunks)monai/networks/layers/vector_quantizer.py(4 hunks)monai/networks/nets/ahnet.py(1 hunks)monai/networks/nets/autoencoderkl.py(2 hunks)monai/networks/nets/basic_unet.py(1 hunks)monai/networks/nets/dints.py(4 hunks)monai/networks/nets/dynunet.py(5 hunks)monai/networks/nets/netadapter.py(2 hunks)monai/networks/nets/quicknat.py(3 hunks)monai/networks/nets/resnet.py(1 hunks)monai/networks/nets/segresnet_ds.py(3 hunks)monai/networks/nets/senet.py(1 hunks)monai/networks/nets/spade_network.py(3 hunks)monai/networks/nets/swin_unetr.py(1 hunks)monai/networks/nets/vista3d.py(6 hunks)monai/networks/nets/vqvae.py(3 hunks)monai/networks/schedulers/rectified_flow.py(1 hunks)monai/networks/trt_compiler.py(6 hunks)monai/networks/utils.py(1 hunks)
✅ Files skipped from review due to trivial changes (3)
- monai/networks/utils.py
- monai/networks/nets/swin_unetr.py
- monai/networks/blocks/attention_utils.py
🚧 Files skipped from review as they are similar to previous changes (1)
- .pre-commit-config.yaml
🧰 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/networks/blocks/crossattention.pymonai/networks/nets/senet.pymonai/networks/blocks/mlp.pymonai/networks/schedulers/rectified_flow.pymonai/networks/blocks/patchembedding.pymonai/networks/nets/spade_network.pymonai/networks/nets/vista3d.pymonai/networks/blocks/spatialattention.pymonai/networks/layers/utils.pymonai/networks/blocks/transformerblock.pymonai/networks/layers/simplelayers.pymonai/networks/blocks/denseblock.pymonai/networks/nets/vqvae.pymonai/networks/nets/netadapter.pymonai/networks/nets/autoencoderkl.pymonai/apps/detection/utils/anchor_utils.pymonai/networks/nets/dints.pymonai/networks/nets/ahnet.pymonai/networks/nets/resnet.pymonai/networks/blocks/selfattention.pymonai/networks/trt_compiler.pymonai/networks/nets/dynunet.pymonai/networks/blocks/pos_embed_utils.pymonai/networks/nets/quicknat.pymonai/networks/layers/vector_quantizer.pymonai/networks/nets/segresnet_ds.pymonai/networks/blocks/rel_pos_embedding.pymonai/networks/nets/basic_unet.py
🪛 Ruff (0.14.3)
monai/networks/nets/spade_network.py
159-159: Avoid specifying long messages outside the exception class
(TRY003)
258-258: Avoid specifying long messages outside the exception class
(TRY003)
monai/networks/nets/resnet.py
243-243: Avoid specifying long messages outside the exception class
(TRY003)
⏰ 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: min-dep-pytorch (2.7.1)
- GitHub Check: min-dep-pytorch (2.6.0)
- GitHub Check: min-dep-pytorch (2.5.1)
- GitHub Check: min-dep-pytorch (2.8.0)
- GitHub Check: min-dep-py3 (3.12)
- GitHub Check: min-dep-py3 (3.10)
- GitHub Check: min-dep-py3 (3.11)
- GitHub Check: min-dep-py3 (3.9)
- GitHub Check: min-dep-os (windows-latest)
- GitHub Check: min-dep-os (macOS-latest)
- GitHub Check: min-dep-os (ubuntu-latest)
- GitHub Check: packaging
- GitHub Check: flake8-py3 (mypy)
- GitHub Check: flake8-py3 (codeformat)
- GitHub Check: quick-py3 (macOS-latest)
- GitHub Check: quick-py3 (windows-latest)
- GitHub Check: quick-py3 (ubuntu-latest)
- GitHub Check: flake8-py3 (pytype)
- GitHub Check: build-docs
🔇 Additional comments (58)
monai/networks/blocks/spatialattention.py (1)
48-48: Type annotation modernization looks good.PEP 604 union syntax applied correctly. Semantically equivalent to
Optional[torch.dtype].monai/networks/blocks/denseblock.py (1)
14-14: PEP 585 modernization applied correctly.Import updated to use
collections.abc.Sequenceinstead oftyping.Sequence. This is the recommended practice for Python 3.9+ and aligns with Ruff's UP rule.monai/networks/nets/spade_network.py (1)
14-14: LGTM: Import modernization.Switching from
typing.Sequencetocollections.abc.Sequencealigns with PEP 585 and Ruff's UP rules.monai/networks/layers/vector_quantizer.py (2)
14-14: LGTM: Import modernization correct.The shift from
typing.Tupleto built-intupleandtyping.Sequencetocollections.abc.Sequencealigns with Python 3.9+ best practices.
90-90: LGTM: Type hint modernization consistent.All
Tuple[...]annotations correctly updated to built-intuple[...]syntax. Non-functional changes only.Also applies to: 167-167, 214-214
monai/networks/blocks/pos_embed_utils.py (2)
35-35: Type hints modernized correctly.PEP 604 union syntax and built-in generics applied properly.
88-88: Type hint modernized correctly.PEP 604 union syntax applied properly.
monai/networks/blocks/patchembedding.py (1)
56-56: Type hint modernized correctly.
Optional[dict]→dict | Noneis semantically equivalent and follows PEP 604.monai/apps/detection/utils/anchor_utils.py (3)
42-42: Import modernization correct.The shift to
collections.abc.Sequenceand removal oftyping.Listaligns with built-in generics usage throughout the file.
109-109: Type annotation correctly applied.Explicit
__annotations__declaration avoids unintended class attribute creation innn.Modulewhile providing type information. Matches actual usage at line 139.
367-367: Type annotation correctly applied.Consistent with parent class pattern. Matches actual usage at line 389.
monai/networks/layers/simplelayers.py (1)
16-16: LGTM—Standard library import modernization.The move from
typing.Sequencetocollections.abc.Sequencealigns with Python 3.9+ best practices.monai/networks/nets/senet.py (1)
122-122: LGTM—F-string modernization.The error message is now clearer and follows modern Python conventions.
monai/networks/nets/autoencoderkl.py (2)
190-190: LGTM—Built-in generic type.Using
list[nn.Module]instead ofList[nn.Module]is the modern approach for Python 3.9+.
340-340: LGTM—Built-in generic type.Consistent with the modernization in Encoder (line 190).
monai/networks/nets/resnet.py (1)
243-243: LGTM—F-string modernization.The error message formatting is now consistent with modern Python practices.
monai/networks/nets/ahnet.py (3)
141-141: LGTM—Modern union syntax.The
bool | Nonesyntax is cleaner and aligns with Python 3.10+ conventions.
177-177: LGTM—Modern union syntax.Consistent with the change in UpTransition (line 141).
288-288: LGTM—Modern union syntax.Consistent type hint modernization throughout the file.
monai/networks/blocks/crossattention.py (2)
43-45: LGTM—Type hint modernization.The constructor parameters now use the modern
X | Nonesyntax, consistent with Python 3.10+.
136-136: LGTM—Type hint modernization.The forward method signature is now consistent with the constructor's type hint style.
monai/networks/nets/basic_unet.py (1)
152-152: LGTM—Type hint modernization.The forward signature now uses modern union syntax. The docstring correctly reflects that
x_eis optional.monai/networks/blocks/transformerblock.py (1)
93-93: LGTM—Type hint modernization.Both optional parameters now use the modern
X | Nonesyntax.monai/networks/layers/utils.py (1)
130-130: Type annotation modernization looks good.The change from
Optional[tuple]totuple | Noneis semantically equivalent and aligns with PEP 604.monai/networks/blocks/rel_pos_embedding.py (2)
12-12: Import modernization is correct.Moving
Iterablefromtypingtocollections.abcfollows current best practices.
22-22: Type annotation update is correct.Built-in
tuplegeneric with union syntax is semantically equivalent to the previous annotation.monai/networks/trt_compiler.py (4)
21-21: Import cleanup is appropriate.Removing unused typing imports after modernization keeps the module clean.
244-246: Function signature modernization is correct.Parameter and return type annotations properly use built-in generics and union syntax.
604-605: Parameter type updates look good.Using
dict[str, Any] | Noneandstr | list[str] | Nonealigns with modern typing conventions.
628-628: Variable annotation is correctly updated.
dict[str, Any]is the modern equivalent ofDict[str, Any].monai/networks/nets/vqvae.py (3)
109-109: Type annotation properly modernized.Using built-in
tuplewithSequenceis the correct approach.
200-200: Type annotation update is correct.Consistent use of built-in
tuplegeneric across the codebase.
314-319: Parameter type annotations properly updated.Both
downsample_parametersandupsample_parametersuse consistent modern typing.monai/networks/nets/dints.py (4)
43-43: Interface signature modernization is correct.The union syntax maintains the same semantics for optional parameters.
177-177: Forward signature properly updated.Consistent with the interface definition.
305-305: Type annotation matches interface.Consistent use of union syntax across all forward method signatures.
576-577: F-string conversion improves readability.The f-string syntax is clearer than string concatenation for formatted output.
monai/networks/blocks/selfattention.py (3)
43-43: Parameter type annotation properly updated.Using
tuple | Noneis consistent with modern Python typing.
103-112: Attribute type annotations correctly modernized.All attribute annotations use union syntax consistently across
out_proj,qkv,to_q,to_k, andto_v.
155-155: Forward method signature properly updated.The optional
attn_maskparameter type is correctly expressed with union syntax.monai/networks/nets/segresnet_ds.py (3)
390-390: Return type annotation properly modernized.Using
None | torch.Tensor | list[torch.Tensor]correctly expresses the possible return types.
426-426: Forward method return type is consistent.Matches the
_forwardimplementation signature.
487-487: Complex return type properly expressed.The tuple of unions correctly represents the dual-branch output structure.
monai/networks/nets/dynunet.py (5)
14-15: Import updates are correct.Moving
Sequencetocollections.abcand removingList,Tuplefromtypingaligns with modern practices.
36-36: Attribute type annotation properly updated.Using
Optional[list[torch.Tensor]]is correct.
140-142: Parameter type annotations modernized.Using built-in
tuplefordropout,norm_name, andact_nameis correct.
173-173: Initialization annotation correctly updated.
list[torch.Tensor]properly replacesList[torch.Tensor].
327-328: Method signature parameters properly typed.Using
list[int]for channel parameters is the modern equivalent.monai/networks/nets/quicknat.py (3)
14-14: LGTM: Import modernization is correct.Switching to
collections.abc.Sequenceand removing unusedtypingimports after type hint updates is appropriate.
126-127: LGTM: Type hints correctly modernized.
Optional[X]→X | Noneis a correct PEP 604 modernization with no behavioral change.
363-364: LGTM: Type hints correctly modernized.
Union[Tuple, str]→tuple | strmodernizes to PEP 604 syntax and replaces deprecated unparameterizedTuplewith builtintuple.monai/networks/nets/vista3d.py (6)
15-16: LGTM. Import modernization aligns with PEP 604.The removal of
TupleandOptionalfrom typing and addition ofSequencefrom collections.abc correctly supports the built-in generic type hints used throughout the file.
695-695: LGTM. Return type modernized correctly.
772-772: LGTM. Return type modernized correctly.
876-876: LGTM. Parameter type modernized correctly.
894-894: Inconsistency: AI summary claims torch.torch.Tensor was fixed.The summary states
coords_inputtype was updated fromtorch.torch.Tensortotorch.Tensor, but the code still containstorch.torch.Tensorat lines 882, 894, 910, 911.
910-910: LGTM. Parameter type modernized correctly.The
image_sizeparameter type change fromTuple[int, int, int]totuple[int, int, int]is correct (separate from the torch.torch.Tensor issue flagged above).monai/networks/nets/netadapter.py (1)
14-14: Import cleanup aligns with built-in generic usage.Removing
Dictis correct since line 112 now usesdict[str, torch.Tensor].
Signed-off-by: jirka <[email protected]>
sure, will do it shortly :) |
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.
Pull request overview
This PR replaces the pyupgrade pre-commit hook with Ruff's built-in UP (pyupgrade) rule, simplifying the linting toolchain while maintaining all the same code modernization capabilities. The changes apply Python 3.9+ syntax improvements across the codebase.
Key changes:
- Removed
pyupgradefrom.pre-commit-config.yamland enabled Ruff's "UP" rule inpyproject.toml - Modernized type hints using PEP 604 syntax (Union[X, Y] → X | Y, Optional[X] → X | None)
- Converted imports from
typingtocollections.abcfor standard collection types - Updated string formatting from % and .format() to f-strings
- Simplified redundant function calls (
float()on literals,lru_cache(maxsize=None)→cache)
Reviewed changes
Copilot reviewed 47 out of 47 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| .pre-commit-config.yaml | Removed pyupgrade hook and simplified Ruff exclusions since typing rewrites are now allowed |
| pyproject.toml | Added "UP" (pyupgrade) rule to Ruff's select list |
| tests/profile_subclass/profiling.py | Converted .format() to f-strings for print statements |
| monai/transforms/utility/array.py | Removed Union import, modernized type hints to use pipe operator |
| monai/networks/utils.py | Moved Iterable import from typing to collections.abc |
| monai/networks/trt_compiler.py | Removed typing imports (Dict, List, Tuple, Union), converted all type hints to builtin generics |
| monai/networks/schedulers/rectified_flow.py | Removed Union import, converted Optional[X] to X | None |
| monai/networks/nets/vqvae.py | Removed Tuple import, converted Tuple to builtin tuple |
| monai/networks/nets/vista3d.py | Moved Sequence to collections.abc, removed Optional/Tuple, modernized type hints |
| monai/networks/nets/swin_unetr.py | Removed redundant float() calls on numeric literals |
| monai/networks/nets/spade_network.py | Moved Sequence to collections.abc, converted % formatting to f-strings |
| monai/networks/nets/senet.py | Converted % formatting to f-strings |
| monai/networks/nets/segresnet_ds.py | Removed Union import, converted Union[None, X, Y] to None | X | Y |
| monai/networks/nets/resnet.py | Converted % formatting to f-strings |
| monai/networks/nets/quicknat.py | Removed typing imports, modernized Optional and Union type hints |
| monai/networks/nets/netadapter.py | Removed Dict import, converted Dict to builtin dict |
| monai/networks/nets/dynunet.py | Added collections.abc import, converted List/Tuple to builtin generics |
| monai/networks/nets/dints.py | Removed Optional import, converted .format() to f-strings, modernized type hints |
| monai/networks/nets/basic_unet.py | Removed Optional import, modernized type hints |
| monai/networks/nets/autoencoderkl.py | Removed List import, converted List to builtin list |
| monai/networks/nets/ahnet.py | Removed Union import, converted Union type hints |
| monai/networks/layers/vector_quantizer.py | Moved Sequence to collections.abc, removed Tuple, converted return types |
| monai/networks/layers/utils.py | Removed Optional import, converted Optional to pipe syntax |
| monai/networks/layers/simplelayers.py | Moved Sequence import from typing to collections.abc |
| monai/networks/blocks/transformerblock.py | Removed Optional import, converted Optional parameters |
| monai/networks/blocks/spatialattention.py | Removed Optional import, modernized type hints |
| monai/networks/blocks/selfattention.py | Removed Optional/Tuple/Union imports, converted all type hints |
| monai/networks/blocks/rel_pos_embedding.py | Moved Iterable to collections.abc, removed Tuple, modernized hints |
| monai/networks/blocks/pos_embed_utils.py | Removed List/Union imports, converted to builtin generics |
| monai/networks/blocks/patchembedding.py | Removed Optional import, converted Optional type hints |
| monai/networks/blocks/mlp.py | Removed Union import, converted Union type annotations |
| monai/networks/blocks/denseblock.py | Moved Sequence from typing to collections.abc |
| monai/networks/blocks/crossattention.py | Removed Optional/Tuple imports, modernized type hints |
| monai/networks/blocks/attention_utils.py | Removed Tuple import, converted Tuple to builtin tuple |
| monai/metrics/utils.py | Changed lru_cache(maxsize=None) to cache decorator |
| monai/losses/sure_loss.py | Removed Optional import, converted Optional type hints |
| monai/losses/spatial_mask.py | Removed Optional import, modernized type hints |
| monai/losses/perceptual.py | Converted % formatting to .format() (inconsistent with other changes) |
| monai/losses/focal_loss.py | Removed Optional import, converted Optional type hints |
| monai/losses/ds_loss.py | Removed Union import, converted Union type hints |
| monai/losses/dice.py | Converted % formatting to f-strings, fixed typo (missing quote) |
| monai/losses/adversarial_loss.py | Converted % formatting to f-strings |
| monai/handlers/tensorboard_handlers.py | Converted .format() to f-strings |
| monai/handlers/stats_handler.py | Converted .format() to f-strings |
| monai/apps/nnunet/nnunet_bundle.py | Removed typing imports, modernized all type hints |
| monai/apps/detection/utils/anchor_utils.py | Removed List import, converted List to builtin list |
| monai/apps/deepgrow/dataset.py | Converted multi-line .format() calls to multi-line f-strings |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
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 (2)
monai/networks/nets/netadapter.py (1)
14-14: TorchScript incompatible with PEP 585 syntax.Line 112 uses
dict[str, torch.Tensor]intorch.jit.isinstance, which TorchScript doesn't support. Revert totyping.Dict[str, torch.Tensor]and restore theDictimport at line 14.Based on past review: PyTorch 2.4 TorchScript requires
typing.Dict, not built-in generics.🔎 Proposed fix
-from typing import Any +from typing import Any, Dict- elif torch.jit.isinstance(x, dict[str, torch.Tensor]): + elif torch.jit.isinstance(x, Dict[str, torch.Tensor]):Also applies to: 112-112
monai/networks/schedulers/rectified_flow.py (1)
283-297: Docstring still uses old Union syntax.Line 293 documents
Union[int, None]while the signature now usesint | None. Update to match.Fix
- next_timestep (Union[int, None]): Optional next timestep. + next_timestep (int | None): Optional next timestep.
🧹 Nitpick comments (3)
monai/networks/blocks/pos_embed_utils.py (2)
45-48: Update docstrings to match lowercaselistin type hints.Lines 45 and 48 use capital
Listbut the actual type hints use lowercaselist.Suggested fix
- grid_size (int | List[int]): The size of the grid in each spatial dimension. + grid_size (int | list[int]): The size of the grid in each spatial dimension. embed_dim (int): The dimension of the embedding. spatial_dims (int): The number of spatial dimensions (2 for 2D, 3 for 3D). - scales (float | List[float]): The scale for every spatial dimension. If a single float is provided, + scales (float | list[float]): The scale for every spatial dimension. If a single float is provided, the same scale is used for all dimensions.
95-95: Update docstring to match type hint.Docstring should be
int | list[int]to match the actual type hint at line 88.Suggested fix
- grid_size (List[int]): The size of the grid in each spatial dimension. + grid_size (int | list[int]): The size of the grid in each spatial dimension.monai/networks/nets/dints.py (1)
575-578: F-string conversion is correct, but could be consolidated.The split across two f-strings is valid but unnecessary. Consider using a single f-string for clarity.
🔎 Optional consolidation
print( - f"{datetime.datetime.now()}" - f" - Length of input patch is recommended to be a multiple of {2 ** (num_depths + int(use_downsample)):d}." + f"{datetime.datetime.now()} - Length of input patch is recommended to be a multiple of {2 ** (num_depths + int(use_downsample)):d}." )
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting
📒 Files selected for processing (35)
.pre-commit-config.yamlmonai/apps/detection/utils/anchor_utils.pymonai/losses/ds_loss.pymonai/losses/perceptual.pymonai/metrics/utils.pymonai/networks/blocks/attention_utils.pymonai/networks/blocks/crossattention.pymonai/networks/blocks/denseblock.pymonai/networks/blocks/mlp.pymonai/networks/blocks/patchembedding.pymonai/networks/blocks/pos_embed_utils.pymonai/networks/blocks/rel_pos_embedding.pymonai/networks/blocks/selfattention.pymonai/networks/blocks/spatialattention.pymonai/networks/blocks/transformerblock.pymonai/networks/layers/simplelayers.pymonai/networks/layers/utils.pymonai/networks/layers/vector_quantizer.pymonai/networks/nets/ahnet.pymonai/networks/nets/autoencoderkl.pymonai/networks/nets/basic_unet.pymonai/networks/nets/dints.pymonai/networks/nets/dynunet.pymonai/networks/nets/netadapter.pymonai/networks/nets/quicknat.pymonai/networks/nets/resnet.pymonai/networks/nets/segresnet_ds.pymonai/networks/nets/senet.pymonai/networks/nets/spade_network.pymonai/networks/nets/swin_unetr.pymonai/networks/nets/vista3d.pymonai/networks/nets/vqvae.pymonai/networks/schedulers/rectified_flow.pymonai/networks/trt_compiler.pymonai/networks/utils.py
🚧 Files skipped from review as they are similar to previous changes (18)
- monai/networks/nets/autoencoderkl.py
- monai/losses/perceptual.py
- monai/networks/blocks/mlp.py
- monai/networks/nets/swin_unetr.py
- monai/networks/nets/vqvae.py
- monai/networks/layers/simplelayers.py
- monai/metrics/utils.py
- monai/networks/blocks/denseblock.py
- monai/networks/utils.py
- monai/networks/nets/basic_unet.py
- monai/networks/nets/vista3d.py
- monai/networks/blocks/selfattention.py
- monai/networks/blocks/patchembedding.py
- monai/apps/detection/utils/anchor_utils.py
- monai/networks/trt_compiler.py
- monai/networks/blocks/attention_utils.py
- monai/networks/nets/segresnet_ds.py
- monai/networks/nets/quicknat.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/networks/layers/vector_quantizer.pymonai/losses/ds_loss.pymonai/networks/nets/resnet.pymonai/networks/blocks/spatialattention.pymonai/networks/nets/spade_network.pymonai/networks/layers/utils.pymonai/networks/blocks/transformerblock.pymonai/networks/blocks/pos_embed_utils.pymonai/networks/blocks/crossattention.pymonai/networks/nets/dynunet.pymonai/networks/nets/netadapter.pymonai/networks/nets/senet.pymonai/networks/nets/dints.pymonai/networks/schedulers/rectified_flow.pymonai/networks/nets/ahnet.pymonai/networks/blocks/rel_pos_embedding.py
🧬 Code graph analysis (1)
monai/networks/layers/vector_quantizer.py (1)
monai/networks/nets/vqvae.py (1)
quantize(438-440)
🪛 Ruff (0.14.10)
monai/networks/nets/resnet.py
243-243: Avoid specifying long messages outside the exception class
(TRY003)
monai/networks/nets/spade_network.py
159-159: Avoid specifying long messages outside the exception class
(TRY003)
258-258: Avoid specifying long messages outside the exception class
(TRY003)
⏰ 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). (21)
- GitHub Check: CodeQL analysis (python)
- GitHub Check: Agent
- GitHub Check: quick-py3 (windows-latest)
- GitHub Check: packaging
- GitHub Check: quick-py3 (macOS-latest)
- GitHub Check: flake8-py3 (pytype)
- GitHub Check: quick-py3 (ubuntu-latest)
- GitHub Check: flake8-py3 (codeformat)
- GitHub Check: flake8-py3 (mypy)
- GitHub Check: build-docs
- GitHub Check: min-dep-pytorch (2.7.1)
- GitHub Check: min-dep-py3 (3.12)
- GitHub Check: min-dep-pytorch (2.5.1)
- GitHub Check: min-dep-py3 (3.11)
- 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-pytorch (2.8.0)
- GitHub Check: min-dep-os (windows-latest)
- GitHub Check: min-dep-os (macOS-latest)
- GitHub Check: min-dep-os (ubuntu-latest)
🔇 Additional comments (26)
monai/networks/nets/senet.py (1)
122-122: LGTM - f-string modernization.Error message formatting updated correctly as part of the broader pyupgrade → Ruff migration.
monai/networks/nets/resnet.py (1)
243-243: LGTM - f-string modernization.Error message formatting updated correctly as part of the broader pyupgrade → Ruff migration. The Ruff TRY003 hint can be ignored; the message is specific and clear.
monai/networks/nets/spade_network.py (3)
14-14: LGTM: Import modernizationCorrect migration from
typing.Sequencetocollections.abc.Sequenceper PEP 585.
159-159: f-string conversion correct; Ruff TRY003 is pedantic hereThe f-string improves readability. Ruff's TRY003 hint suggests moving the message to a custom exception class, but that's overkill for a simple validation error.
258-258: f-string conversion correct; Ruff TRY003 is pedantic hereSame as line 159: f-string improves readability, and the Ruff TRY003 hint is overly pedantic for this simple validation.
monai/networks/blocks/pos_embed_utils.py (2)
35-35: LGTM - type hints modernized correctly.PEP 604 union syntax with built-in generics is appropriate. The
__future__import at line 12 ensures compatibility.
88-88: LGTM - type hint modernized correctly.Consistent with the changes in
build_fourier_position_embedding.monai/networks/nets/ahnet.py (1)
141-141: LGTM - type hint modernization applied consistently.The three instances correctly update
Union[bool, None]tobool | Nonesyntax. No behavioral changes.Also applies to: 177-177, 288-288
monai/networks/nets/dints.py (3)
43-43: Type annotation modernized correctly.PEP 604 union syntax is appropriate here.
177-177: Type annotation modernized correctly.The implementation properly handles the None case.
305-305: Type annotation modernized correctly.Signature properly matches the interface definition.
monai/networks/blocks/crossattention.py (2)
42-44: Type annotations modernized correctly.The parameter type hints now use Python 3.10+ union syntax (
X | Noneinstead ofOptional[X],tupleinstead ofTuple). No behavioral changes.
135-135: Forward signature updated consistently.The
contextparameter type annotation follows the same modernization pattern.monai/networks/blocks/spatialattention.py (1)
47-47: Type annotation modernized.Consistent with Python 3.10+ style.
monai/losses/ds_loss.py (1)
71-71: Union syntax modernized.Changed to PEP 604 style (
|operator). No runtime impact.monai/networks/nets/dynunet.py (2)
14-15: Import modernization.Added
collections.abc.Sequence, updated typing imports to support builtin generics.
36-36: Type annotations use builtin generics.Changed
List→list,Tuple→tuplethroughout. Consistent with Python 3.10+ style.Also applies to: 140-142, 173-173, 327-328
monai/networks/layers/utils.py (1)
129-129: Signature updated with modern union syntax.Changed
Optional[tuple]totuple | None.monai/networks/blocks/transformerblock.py (1)
92-92: Forward parameters modernized.Both
contextandattn_maskuseX | Nonesyntax.monai/networks/blocks/rel_pos_embedding.py (2)
12-12: Import moved to collections.abc.Preferred source for
Iterablein modern Python.
22-22: Builtin tuple type used.Changed
Tuple→tuplein union type annotation.monai/networks/layers/vector_quantizer.py (4)
14-14: Import modernization is correct.Moved
Sequencetocollections.abcper Python 3.9+ conventions. Removed unusedTupleimport.
90-90: Return type annotation modernized correctly.Changed to built-in
tuple[...]syntax. Matches docstring and actual return statement.
167-167: Return type annotation updated correctly.Built-in
tuple[...]matches the three-tensor return at line 194.
214-214: Return type annotation modernized correctly.Changed to built-in
tuple[...]. Consistent with return at line 225 and related code in vqvae.py..pre-commit-config.yaml (1)
34-38: Versioneer files are already properly excluded. The exclude pattern correctly matches bothversioneer.pyandmonai/_version.py. Ruff UP rules are properly configured inpyproject.toml. No changes needed to the exclude pattern.Likely an incorrect or invalid review comment.
Co-authored-by: Copilot <[email protected]> Signed-off-by: Jirka Borovec <[email protected]>
|
trying to unblock CI in #8673 |
|
Hi @Borda we're working on the CICD issue, let's see if we've sorted things here. |
Yeah, seems my PR with fix was merged 😏 |
Signed-off-by: jirka <[email protected]>
Signed-off-by: jirka <[email protected]>
|
FYI, some linting issues were reported in #8683 |
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: 1
Fix all issues with AI Agents 🤖
In @runtests.sh:
- Around line 609-611: The --exclude glob for ruff in the ruff check invocations
is using a regex-style caret ("^monai/_version.py") which won't match as
intended; update both ruff check --exclude entries to use a glob pattern (e.g.,
"monai/_version.py" or "**/monai/_version.py") so the monai/_version.py file is
correctly excluded when running the ruff check commands.
🧹 Nitpick comments (1)
monai/apps/detection/utils/detector_utils.py (1)
94-94: Inconsistent spacing in similar expressions.Line 94 now has
{2 * spatial_dims}(with space), but line 98 still has{2* spatial_dims}(no space). Apply the same spacing for consistency.🔎 Proposed fix
- f"Expected target boxes to be a tensor of shape [N, {2* spatial_dims}], got {boxes.shape}.)." + f"Expected target boxes to be a tensor of shape [N, {2 * spatial_dims}], got {boxes.shape}.)."Also applies to: 98-98
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting
📒 Files selected for processing (11)
monai/apps/auto3dseg/bundle_gen.pymonai/apps/detection/networks/retinanet_detector.pymonai/apps/detection/utils/detector_utils.pyruntests.shtests/data/test_video_datasets.pytests/transforms/test_load_image.pytests/transforms/test_load_imaged.pytests/transforms/test_resample_to_match.pytests/transforms/test_resample_to_matchd.pytests/transforms/test_transform.pytests/utils/misc/test_monai_env_vars.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:
tests/transforms/test_resample_to_matchd.pytests/transforms/test_transform.pytests/utils/misc/test_monai_env_vars.pytests/transforms/test_load_image.pytests/data/test_video_datasets.pymonai/apps/detection/utils/detector_utils.pymonai/apps/auto3dseg/bundle_gen.pymonai/apps/detection/networks/retinanet_detector.pytests/transforms/test_resample_to_match.pytests/transforms/test_load_imaged.py
🧬 Code graph analysis (6)
tests/transforms/test_transform.py (1)
tests/utils/misc/test_monai_env_vars.py (2)
setUpClass(23-25)tearDownClass(28-34)
tests/utils/misc/test_monai_env_vars.py (6)
tests/data/test_video_datasets.py (1)
setUpClass(101-126)tests/transforms/test_load_image.py (4)
setUpClass(190-201)setUpClass(473-478)tearDownClass(204-206)tearDownClass(481-483)tests/transforms/test_load_imaged.py (2)
setUpClass(159-166)tearDownClass(169-171)tests/transforms/test_resample_to_match.py (2)
setUpClass(50-60)tearDownClass(63-65)tests/transforms/test_resample_to_matchd.py (2)
setUpClass(40-50)tearDownClass(53-55)tests/transforms/test_transform.py (2)
setUpClass(35-37)tearDownClass(40-45)
tests/data/test_video_datasets.py (6)
tests/transforms/test_load_image.py (2)
setUpClass(190-201)setUpClass(473-478)tests/transforms/test_load_imaged.py (1)
setUpClass(159-166)tests/transforms/test_resample_to_match.py (1)
setUpClass(50-60)tests/transforms/test_resample_to_matchd.py (1)
setUpClass(40-50)tests/transforms/test_transform.py (1)
setUpClass(35-37)tests/utils/misc/test_monai_env_vars.py (1)
setUpClass(23-25)
monai/apps/detection/networks/retinanet_detector.py (1)
monai/transforms/utils_pytorch_numpy_unification.py (1)
max(461-481)
tests/transforms/test_resample_to_match.py (4)
tests/transforms/test_load_imaged.py (2)
setUpClass(159-166)tearDownClass(169-171)tests/transforms/test_resample_to_matchd.py (2)
setUpClass(40-50)tearDownClass(53-55)tests/transforms/test_transform.py (2)
setUpClass(35-37)tearDownClass(40-45)tests/utils/misc/test_monai_env_vars.py (2)
setUpClass(23-25)tearDownClass(28-34)
tests/transforms/test_load_imaged.py (2)
tests/transforms/test_resample_to_match.py (2)
setUpClass(50-60)tearDownClass(63-65)tests/utils/misc/test_monai_env_vars.py (2)
setUpClass(23-25)tearDownClass(28-34)
⏰ 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: min-dep-py3 (3.11)
- GitHub Check: min-dep-os (windows-latest)
- GitHub Check: min-dep-pytorch (2.8.0)
- GitHub Check: min-dep-py3 (3.12)
- GitHub Check: min-dep-os (macOS-latest)
- GitHub Check: min-dep-py3 (3.10)
- GitHub Check: min-dep-os (ubuntu-latest)
- GitHub Check: min-dep-pytorch (2.7.1)
- GitHub Check: min-dep-pytorch (2.5.1)
- GitHub Check: min-dep-py3 (3.9)
- GitHub Check: min-dep-pytorch (2.6.0)
- GitHub Check: quick-py3 (ubuntu-latest)
- GitHub Check: flake8-py3 (mypy)
- GitHub Check: flake8-py3 (pytype)
- GitHub Check: flake8-py3 (codeformat)
- GitHub Check: build-docs
- GitHub Check: packaging
- GitHub Check: quick-py3 (windows-latest)
- GitHub Check: quick-py3 (macOS-latest)
🔇 Additional comments (10)
monai/apps/auto3dseg/bundle_gen.py (1)
399-399: LGTM! Formatting consistency improved.Spacing around the
+operator aligns with PEP 8. No functional impact.monai/apps/detection/networks/retinanet_detector.py (1)
790-790: LGTM — formatting improvement.Proper spacing after comma aligns with PEP 8.
tests/transforms/test_load_imaged.py (1)
160-160: LGTM - Modern super() syntax.Correct Python 3 modernization. No behavioral change.
Also applies to: 171-171
tests/transforms/test_resample_to_match.py (1)
51-51: LGTM - Modern super() syntax.Correct Python 3 modernization. No behavioral change.
Also applies to: 65-65
tests/transforms/test_resample_to_matchd.py (1)
41-41: LGTM - Modern super() syntax.Correct Python 3 modernization. No behavioral change.
Also applies to: 55-55
tests/data/test_video_datasets.py (1)
102-102: LGTM - Modern super() syntax.Correct Python 3 modernization. No behavioral change.
tests/utils/misc/test_monai_env_vars.py (1)
24-24: LGTM - Modern super() syntax.Correct Python 3 modernization. No behavioral change.
Also applies to: 34-34
tests/transforms/test_load_image.py (1)
191-191: LGTM: Modern super() syntax.The simplified
super()form is correct and preferred for Python 3+.Also applies to: 206-206, 474-474, 483-483
tests/transforms/test_transform.py (1)
36-36: LGTM: Modern super() syntax.Consistent with Python 3+ best practices and other test files in the codebase.
Also applies to: 45-45
runtests.sh (1)
609-609: Confirm understanding of risks from--unsafe-fixes.The
--unsafe-fixesflag applies fixes that may alter runtime behavior or remove comments. Ensure the team has reviewed what changes this enables for the UP rule migration and explicitly accepts the risk.
Signed-off-by: jirka <[email protected]>
Signed-off-by: jirka <[email protected]>
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: 2
Fix all issues with AI Agents 🤖
In @monai/networks/nets/spade_network.py:
- Around line 260-264: The error message in the divisibility check inside
spade_network.py is misleading: when the condition in the block that raises
ValueError (the check using s_ / (2 ** len(channels)) != s_ // (2 **
len(channels))) fails, update the ValueError text to state the correct divisor
"2 ** {len(channels)}" instead of "{len(channels)}"; adjust the f-string in that
raise in the same style as the encoder fix so it reads that the shape at
position {s_ind}, {s_} is not divisible by 2 ** {len(channels)} and retains the
surrounding context text.
- Around line 162-165: The ValueError message in spade_network.py inside the
check that raises for input-size divisibility is misleading; update the raise in
the block (the raise ValueError in the input-shape/divisibility check inside the
SPADE network construction) to state that each dimension must be divisible by 2
** len(channels) (or include the computed divisor variable like divisor = 2 **
len(channels) and use it in the message) instead of saying "divisible by
{len(channels)}", and keep the rest of the context (shape position and values)
in the message.
🧹 Nitpick comments (2)
monai/utils/profiling.py (1)
340-340: Remove unusednoqadirective.Ruff reports that
N805is not enabled, making thenoqadirective unnecessary. Clean up by removing it.🔎 Proposed fix
- def __iter__(_self): # noqa: N805 pylint: disable=E0213 + def __iter__(_self): # pylint: disable=E0213monai/networks/nets/spade_network.py (1)
158-165: Consider extracting shared validation logic.The input shape validation (length check + divisibility check) is duplicated between
SPADEEncoderandSPADEDecoder. Extracting to a shared helper would reduce duplication.Also applies to: 257-264
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting
📒 Files selected for processing (11)
monai/networks/nets/ahnet.pymonai/networks/nets/autoencoder.pymonai/networks/nets/densenet.pymonai/networks/nets/fullyconnectednet.pymonai/networks/nets/generator.pymonai/networks/nets/hovernet.pymonai/networks/nets/patchgan_discriminator.pymonai/networks/nets/regressor.pymonai/networks/nets/spade_network.pymonai/utils/profiling.pyruntests.sh
✅ Files skipped from review due to trivial changes (1)
- monai/networks/nets/densenet.py
🚧 Files skipped from review as they are similar to previous changes (1)
- monai/networks/nets/ahnet.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/networks/nets/fullyconnectednet.pymonai/networks/nets/regressor.pymonai/networks/nets/autoencoder.pymonai/networks/nets/generator.pymonai/networks/nets/hovernet.pymonai/networks/nets/patchgan_discriminator.pymonai/utils/profiling.pymonai/networks/nets/spade_network.py
🪛 Ruff (0.14.10)
monai/utils/profiling.py
340-340: Unused noqa directive (non-enabled: N805)
Remove unused noqa directive
(RUF100)
monai/networks/nets/spade_network.py
159-159: Avoid specifying long messages outside the exception class
(TRY003)
258-258: Avoid specifying long messages outside the exception class
(TRY003)
⏰ 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: packaging
- GitHub Check: flake8-py3 (codeformat)
- GitHub Check: flake8-py3 (mypy)
- GitHub Check: quick-py3 (windows-latest)
- GitHub Check: flake8-py3 (pytype)
- GitHub Check: quick-py3 (macOS-latest)
- GitHub Check: quick-py3 (ubuntu-latest)
- GitHub Check: build-docs
- GitHub Check: min-dep-pytorch (2.7.1)
- GitHub Check: min-dep-pytorch (2.6.0)
- GitHub Check: min-dep-py3 (3.10)
- GitHub Check: min-dep-py3 (3.12)
- GitHub Check: min-dep-pytorch (2.8.0)
- GitHub Check: min-dep-os (ubuntu-latest)
- GitHub Check: min-dep-py3 (3.9)
- GitHub Check: min-dep-os (windows-latest)
- GitHub Check: min-dep-pytorch (2.5.1)
- GitHub Check: min-dep-os (macOS-latest)
- GitHub Check: min-dep-py3 (3.11)
🔇 Additional comments (9)
monai/networks/nets/hovernet.py (1)
156-156: LGTM - f-string modernization.Correct conversion from printf-style to f-string formatting. Output identical, style improved.
monai/networks/nets/regressor.py (1)
99-99: LGTM - f-string modernization.Correct conversion. Functionally equivalent.
monai/networks/nets/fullyconnectednet.py (1)
79-79: LGTM - f-string modernization.All three module name conversions correct and functionally equivalent.
Also applies to: 139-139, 147-147
monai/networks/nets/generator.py (1)
100-100: LGTM - f-string modernization.Correct conversion.
monai/networks/nets/autoencoder.py (1)
151-151: LGTM - f-string modernization.All three module name conversions correct and functionally equivalent.
Also applies to: 202-202, 218-218
monai/networks/nets/patchgan_discriminator.py (2)
94-94: LGTM: f-string modernization for module naming.Conversion from
%formatting to f-string is correct and improves readability.
195-195: LGTM: f-string modernization for layer naming.Conversion from
%formatting to f-string is correct and improves readability.runtests.sh (1)
609-611: Exclusion patterns corrected.The glob patterns now correctly exclude versioneer files without regex syntax. The
--unsafe-fixesflag is appropriately applied only when fixing.monai/networks/nets/spade_network.py (1)
14-14: LGTM: Import modernization.Correctly moves from
typing.Sequencetocollections.abc.Sequence.
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.
Pull request overview
Copilot reviewed 63 out of 66 changed files in this pull request and generated 3 comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Signed-off-by: Jirka Borovec <[email protected]>
Signed-off-by: jirka <[email protected]>
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: 1
Fix all issues with AI Agents 🤖
In @monai/losses/sure_loss.py:
- Line 134: Add a unit test constructing SURELoss() with eps=None and verify it
follows the auto-estimation path by comparing outputs to an instance constructed
with eps=-1.0: create deterministic random tensors (seed RNG) for prediction and
target (and perturb_noise if required), compute loss_none = SURELoss()(pred,
target) and loss_auto = SURELoss(eps=-1.0)(pred, target), and assert they are
numerically close (e.g., torch.allclose) so the auto-estimation code path in
__init__/forward/sure_loss_function is exercised and behaves identically to the
explicit -1.0 case.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting
📒 Files selected for processing (1)
monai/losses/sure_loss.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/losses/sure_loss.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). (17)
- GitHub Check: quick-py3 (ubuntu-latest)
- GitHub Check: quick-py3 (windows-latest)
- GitHub Check: packaging
- GitHub Check: flake8-py3 (codeformat)
- GitHub Check: flake8-py3 (mypy)
- GitHub Check: build-docs
- GitHub Check: flake8-py3 (pytype)
- GitHub Check: min-dep-pytorch (2.6.0)
- GitHub Check: min-dep-os (ubuntu-latest)
- GitHub Check: min-dep-pytorch (2.5.1)
- GitHub Check: min-dep-pytorch (2.7.1)
- GitHub Check: min-dep-py3 (3.10)
- GitHub Check: min-dep-py3 (3.12)
- GitHub Check: min-dep-pytorch (2.8.0)
- GitHub Check: min-dep-py3 (3.11)
- GitHub Check: min-dep-py3 (3.9)
- GitHub Check: min-dep-os (windows-latest)
🔇 Additional comments (3)
monai/losses/sure_loss.py (3)
14-14: Import cleanup aligns with modern type hints.Correctly removes unused typing imports now that union syntax is used.
45-48: Type hints corrected per prior feedback.Past review comments flagged
eps: float | None = -1.0andcomplex_input: bool | None = Falseas misleading. Current signatures useeps: float = -1.0andcomplex_input: bool = False, which correctly reflect that -1.0 is the sentinel (not None) and complex_input is boolean (not optional).
152-153: LGTM.Signature changes match sure_loss_function expectations:
y_refcan be None,complex_inputis boolean.
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.
Pull request overview
Copilot reviewed 62 out of 65 changed files in this pull request and generated 3 comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| perturb_noise: Optional[torch.Tensor] = None, | ||
| complex_input: Optional[bool] = False, | ||
| y_ref: torch.Tensor | None = None, | ||
| eps: float = -1.0, |
Copilot
AI
Jan 5, 2026
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.
The change from Optional[float] to a non-optional float parameter with a default value changes the function signature. The original signature explicitly showed that eps could be None, but now it defaults to -1.0. This means that callers who explicitly pass None will now get a type error. This is a breaking change in the API contract.
| complex_input: Optional[bool] = False, | ||
| y_ref: torch.Tensor | None = None, | ||
| eps: float = -1.0, | ||
| perturb_noise: torch.Tensor | None = None, |
Copilot
AI
Jan 5, 2026
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.
Similarly, changing from Optional[torch.Tensor] to a non-optional torch.Tensor parameter with default value changes the function signature. Callers who explicitly pass None will get a type error. This is a breaking change in the API contract.
Co-authored-by: Copilot <[email protected]> Signed-off-by: Jirka Borovec <[email protected]>
simplify the lintong and reduce the number of used tools to increase consistency without any formatting loss
Description
A few sentences describing the changes proposed in this pull request.
Types of changes
./runtests.sh -f -u --net --coverage../runtests.sh --quick --unittests --disttests.make htmlcommand in thedocs/folder.