-
Notifications
You must be signed in to change notification settings - Fork 1.3k
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
|
Warning Rate limit exceeded@Borda has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 0 minutes and 35 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (35)
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. WalkthroughThe diff applies widespread non-functional modernizations: many type hints converted from typing.Union/Optional and typing container aliases to PEP 604 ( Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes
Pre-merge checks and finishing touches❌ Failed checks (2 warnings)
✅ Passed checks (1 passed)
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 <jirka.borovec@seznam.cz>
for more information, see https://pre-commit.ci Signed-off-by: jirka <jirka.borovec@seznam.cz>
Signed-off-by: jirka <jirka.borovec@seznam.cz>
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 <6035284+Borda@users.noreply.github.com>
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 <6035284+Borda@users.noreply.github.com>
Signed-off-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Signed-off-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Signed-off-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Signed-off-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Signed-off-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
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].
| # Use Union[nn.Dropout, nn.Identity] for type annotations | ||
| self.drop1: Union[nn.Dropout, nn.Identity] | ||
| self.drop2: Union[nn.Dropout, nn.Identity] | ||
| self.drop1: nn.Dropout | nn.Identity | ||
| self.drop2: nn.Dropout | nn.Identity |
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.
Outdated comment contradicts implementation.
Line 57 references Union syntax, but lines 58-59 use pipe syntax.
Remove or update the comment:
- # Use Union[nn.Dropout, nn.Identity] for type annotations
self.drop1: nn.Dropout | nn.Identity
self.drop2: nn.Dropout | nn.Identity📝 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.
| # Use Union[nn.Dropout, nn.Identity] for type annotations | |
| self.drop1: Union[nn.Dropout, nn.Identity] | |
| self.drop2: Union[nn.Dropout, nn.Identity] | |
| self.drop1: nn.Dropout | nn.Identity | |
| self.drop2: nn.Dropout | nn.Identity | |
| self.drop1: nn.Dropout | nn.Identity | |
| self.drop2: nn.Dropout | nn.Identity |
🤖 Prompt for AI Agents
In monai/networks/blocks/mlp.py around lines 57 to 59, the comment stating "Use
Union[nn.Dropout, nn.Identity] for type annotations" is outdated because the
code uses Python 3.10+ pipe syntax (self.drop1: nn.Dropout | nn.Identity and
self.drop2: nn.Dropout | nn.Identity); update the comment to reflect the pipe
syntax (e.g., "Use nn.Dropout | nn.Identity for type annotations") or remove the
comment entirely so it no longer contradicts the implementation.
| if isinstance(x, tuple): | ||
| x = x[0] # it might be a namedtuple such as torchvision.model.InceptionOutputs | ||
| elif torch.jit.isinstance(x, Dict[str, torch.Tensor]): | ||
| elif torch.jit.isinstance(x, dict[str, torch.Tensor]): |
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.
🧩 Analysis chain
Verify TorchScript compatibility with built-in generic syntax.
TorchScript's type system historically required typing.Dict for proper type checking. Confirm that torch.jit.isinstance(x, dict[str, torch.Tensor]) works correctly with the project's minimum PyTorch version.
🏁 Script executed:
#!/bin/bash
# Check minimum Python and PyTorch versions, search for other TorchScript type annotations
# Find Python version requirement
rg -n 'python_requires|Programming Language :: Python ::' setup.py setup.cfg pyproject.toml 2>/dev/null || echo "No Python version requirement found"
# Find PyTorch version requirement
rg -n 'torch[=><!]' requirements.txt setup.py setup.cfg pyproject.toml 2>/dev/null | head -20
# Search for other torch.jit.isinstance calls to check consistency
rg -n 'torch\.jit\.isinstance' --type=py -C2Length of output: 1842
---
🌐 Web query:
```web
PyTorch 2.4 TorchScript dict generic type support built-in syntax
💡 Result:
Short answer: No — as of PyTorch 2.4, TorchScript does not use the PEP 585 builtin-generic syntax (e.g. dict[str,int]). Use typing.Dict / typing.List (or the typing aliases) or PEP‑526 annotations (e.g. from typing import Dict; my_dict: Dict[str,int]) for TorchScript types. [1][2]
Sources:
- TorchScript docs showing typing.Dict usage and PEP‑526 attribute annotations. [1]
- PyTorch 2.4 release / TorchScript pages (docs reference behavior across 2.x). [2]
---
🏁 Script executed:
```shell
#!/bin/bash
# Check if netadapter functions are tested with TorchScript
rg -n 'netadapter|NetAdapter' --type=py tests/ 2>/dev/null | head -10
rg -n 'torch.jit.script|torch.jit.trace' tests/ --type=py | head -10
rg -n 'def.*extract' monai/networks/nets/netadapter.py -A5 | head -20
Length of output: 120
Change dict[str, torch.Tensor] to typing.Dict[str, torch.Tensor].
PyTorch 2.4 TorchScript does not support PEP 585 built-in generic syntax. The torch.jit.isinstance() check at line 112 requires typing.Dict instead of dict. This pattern also appears in retinanet_network.py:333 and should be corrected there as well.
🤖 Prompt for AI Agents
In monai/networks/nets/netadapter.py around line 112, the torch.jit.isinstance
check uses PEP 585 syntax `dict[str, torch.Tensor]` which TorchScript (PyTorch
2.4) does not support; replace it with `typing.Dict[str, torch.Tensor]` and add
or ensure `from typing import Dict` (or import typing and use typing.Dict) is
present at the top of the file; also update the same pattern in
monai/networks/nets/retinanet_network.py at line ~333 to use typing.Dict[str,
torch.Tensor].
|
|
||
| def step( | ||
| self, model_output: torch.Tensor, timestep: int, sample: torch.Tensor, next_timestep: Union[int, None] = None | ||
| self, model_output: torch.Tensor, timestep: int, sample: torch.Tensor, next_timestep: int | None = None |
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.
Update docstring to match PEP 604 syntax.
Line 294 still uses Union[int, None] while the signature now uses int | None. Update to int | None or simplify to "Optional next timestep."
- next_timestep (Union[int, None]): Optional next timestep.
+ next_timestep (int | None): Optional next timestep.Also applies to: 294-294
🤖 Prompt for AI Agents
In monai/networks/schedulers/rectified_flow.py around lines 285 to 294, the
function signature uses PEP 604 syntax (int | None) for next_timestep but the
docstring still shows Union[int, None]; update the docstring to match the
signature by replacing "Union[int, None]" with "int | None" or simpler text like
"Optional next timestep" and ensure the parameter description formatting matches
the rest of the docstring.
Signed-off-by: jirka <jirka.borovec@seznam.cz>
Signed-off-by: jirka <jirka.borovec@seznam.cz>
|
There's a few things coderabbit has mentioned that are worth looking at, but the failed checks are all related to versioneer files that should be ignored I think. I'm not sure why from your changes why these aren't being ignored now. All other changes looked fine to me however. |
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.