-
Notifications
You must be signed in to change notification settings - Fork 10
chore: Drop python 3.8 #1206
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
chore: Drop python 3.8 #1206
Conversation
Reviewer's Guide by SourceryThis pull request drops support for Python 3.8 and updates the codebase to use more modern Python syntax, particularly with type annotations. The changes primarily involve updating type hints to use the new syntax introduced in Python 3.9+, such as using Class diagram for updated type annotationsclassDiagram
class ComponentsInfo {
np.ndarray roi_components
np.ndarray mask_components
dict[int, list[int]] components_translation
bool has_components()
}
class MeasurementResult {
ComponentsInfo components_info
OrderedDict _data_dict
dict[str, str] _units_dict
dict[str, tuple[PerComponent, AreaType]] _type_dict
void set_filename(str path_fo_file)
tuple[bool, bool] get_component_info(bool all_components)
list[str] get_labels(bool expand, bool all_components)
list[str] get_units(bool all_components)
list[list[MeasurementValueType]] get_separated(bool all_components)
}
class MaskProjectTuple {
Union[Image, str, None] image
Optional[np.ndarray] mask
ROIInfo roi_info
dict[str, AdditionalLayerDescription] additional_layers
list[int] selected_components
dict[int, Optional[ROIExtractionProfile]] roi_extraction_parameters
list[HistoryElement] history
str errors
Optional[list[float]] spacing
Optional[np.ndarray] points
int frame_thickness
}
class ImageInfo {
Image image
list[NapariImage] layers
list[tuple[NoiseFilterType, float]] filter_info
Optional[Labels] mask
Optional[np.ndarray] mask_array
Optional[Labels] roi
int roi_count
Optional[Labels] highlight
bool coords_in(Union[list[int], np.ndarray] coords)
np.ndarray translated_coords(Union[list[int], np.ndarray] coords)
}
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
WalkthroughThis pull request includes modifications to the workflow files for testing napari widgets, updating Python version compatibility, and adjusting type annotations in several files. The workflows now exclude Python 3.8, focusing on versions 3.9 to 3.12. The napari versions tested have also been updated. Additionally, type annotations have been modernized across various classes and functions, reflecting a shift from the Changes
Possibly related PRs
Suggested labels
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (4)
🚧 Files skipped from review as they are similar to previous changes (4)
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
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.
Hey @Czaki - I've reviewed your changes and they look great!
Here's what I looked at during the review
- 🟢 General issues: all looks good
- 🟢 Security: all looks good
- 🟢 Testing: all looks good
- 🟢 Complexity: all looks good
- 🟢 Documentation: all looks good
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
| self.components_info = components_info | ||
| self._data_dict = OrderedDict() | ||
| self._units_dict: Dict[str, str] = {} | ||
| self._type_dict: Dict[str, Tuple[PerComponent, AreaType]] = {} | ||
| self._units_dict: dict[str, str] = {} | ||
| self._type_dict: dict[str, tuple[PerComponent, AreaType]] = {} | ||
| self._units_dict["Mask component"] = "" | ||
| self._units_dict["Segmentation component"] = "" |
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.
issue (code-quality): We've found these issues:
- Move assignment closer to its usage within a block (
move-assign-in-block) - Merge dictionary assignment with declaration [×2] (
merge-dict-assign)
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: 8
🧹 Outside diff range and nitpick comments (62)
package/PartSegCore/custom_name_generate.py (1)
Line range hint
7-13: LGTM: Function logic remains sound.The function logic for generating custom names remains unchanged and appears to be working as intended. The use of
random.choicefor name generation is appropriate for this use case, and the function includes proper checks against prohibited and existing names.For future consideration: The function's efficiency could potentially be improved by using a more sophisticated method for generating unique names, such as using a combination of timestamp and random characters, or implementing a name generation strategy that reduces the likelihood of collisions. This could help avoid the need for multiple attempts and the potential
RuntimeError. However, this optimization is outside the scope of the current PR and can be considered for future enhancements.package/PartSegCore/image_transforming/swap_time_stack.py (2)
33-33: Approved: Enhanced type hinting with room for further improvementThe change from
typing.Listtolistin the return type hint is a positive update, similar to the previous method. This modification:
- Aligns with modern Python type hinting practices (Python 3.9+).
- Improves code readability.
- Is consistent with the PR objective of dropping Python 3.8 support.
The functionality of the method remains unchanged, making this a safe and beneficial update.
Consider further simplifying the type hint by using
|instead oftyping.Unionfor union types in Python 3.10+:def get_fields(cls) -> list[AlgorithmProperty | str]: return []This change would further modernize the code and improve readability, assuming the project's minimum Python version is 3.10 or higher.
Line range hint
1-35: Overall assessment: Successful modernization of type hintsThe changes in this file successfully contribute to the PR objective of dropping Python 3.8 support by updating type hints to use built-in types instead of the
typingmodule. These modifications improve code readability and align with modern Python practices without altering the functionality of theSwapTimeStackclass.Key points:
- All changes are type hint updates, reducing the risk of introducing bugs.
- The updates are consistent across the file, improving overall code consistency.
- The changes pave the way for potential further modernization in the future.
As the project continues to evolve, consider setting a minimum Python version requirement (e.g., Python 3.9 or 3.10) in the project's documentation and setup files. This will help clarify which Python features can be used throughout the codebase and guide future development and contributions.
.pre-commit-config.yaml (1)
Incomplete Python version compatibility
codespellrequires Python>=3.8, which does not meet the>=3.9requirement.psf/black-pre-commit-mirrordoes not specify a minimum Python version.Please update these hooks to support Python
>=3.9or consider finding alternatives that are compatible.🔗 Analysis chain
Line range hint
1-55: Verify compatibility with updated Python versionWhile updating Black and removing Python 3.8 support are good steps, it's important to ensure that all other pre-commit hooks are compatible with the new minimum Python version.
Please run the following command to check the minimum Python version required by each pre-commit hook:
Review the output to ensure all hooks support Python 3.9 or higher. If any hook doesn't meet this requirement, consider updating it or finding an alternative.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check minimum Python version for each pre-commit hook # Expected: All hooks should support Python 3.9+ for repo in $(grep "repo:" .pre-commit-config.yaml | awk '{print $3}'); do echo "Checking $repo" curl -s "https://raw.githubusercontent.com/${repo#https://github.com/}/master/setup.py" | grep "python_requires" doneLength of output: 2153
Script:
#!/bin/bash # Description: Check minimum Python version for each pre-commit hook by searching for 'python_requires' in 'setup.py' or 'requires-python' in 'pyproject.toml' # Expected: All hooks should support Python 3.9+ for repo in $(grep "repo:" .pre-commit-config.yaml | awk '{print $3}'); do echo "Checking $repo" path=${repo#https://github.com/} # Check setup.py for python_requires setup_py=$(curl -s "https://raw.githubusercontent.com/${path}/master/setup.py") if echo "$setup_py" | grep -E "python_requires\s*=" >/dev/null; then echo "setup.py: $(echo "$setup_py" | grep -E "python_requires\s*=")" continue fi # Check pyproject.toml for requires-python pyproject_toml=$(curl -s "https://raw.githubusercontent.com/${path}/master/pyproject.toml") if echo "$pyproject_toml" | grep -E "requires-python\s*=" >/dev/null; then echo "pyproject.toml: $(echo "$pyproject_toml" | grep -E "requires-python\s*=")" continue fi echo "No Python version requirement found." doneLength of output: 32425
package/PartSegCore/napari_plugins/save_tiff_layer.py (2)
28-28: LGTM: Function signature updated to use built-inlisttype.The change from
Listtolistin the function signature is appropriate and aligns with modern Python type hinting practices for Python 3.9+. This update improves code readability and maintainability without affecting the function's behavior.For consistency, consider updating the
Optional[str]return type hint in thenapari_write_labelsfunction to use the|syntax introduced in Python 3.10 (e.g.,str | None). This would further modernize the codebase if the minimum supported Python version is 3.10 or higher.
Remaining usage of
ListfromtypingdetectedThe following files still utilize
Listfromtypingin type hints. Please update these instances to use the built-inlistfor consistency and to adhere to the modernization efforts of the codebase:
package/PartSeg/_roi_mask/stack_settings.pypackage/PartSeg/common_gui/universal_gui_part.pypackage/PartSegCore/project_info.pypackage/PartSegCore/mask_create.pypackage/PartSegCore/mask/io_functions.pypackage/PartSegCore/analysis/calculation_plan.pypackage/PartSegCore/analysis/measurement_calculation.pypackage/PartSegCore/analysis/batch_processing/batch_backend.pyPlease ensure all instances are updated accordingly to maintain code quality and consistency.
🔗 Analysis chain
Line range hint
1-58: Summary: Type hint updates successfully modernize the code.The changes in this file successfully update the type hints to use built-in types, which is consistent with dropping support for Python 3.8. These updates improve code readability and maintainability without altering the functionality of the
napari_write_labelsandnapari_write_imagesfunctions.To ensure that these changes haven't inadvertently affected other parts of the codebase, please run the following verification script:
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for any remaining usage of typing.List in the codebase # Test: Search for any remaining imports of List from typing echo "Checking for remaining 'from typing import List' statements:" rg --type python "from typing import .*List" # Test: Search for any remaining usage of List as a type hint echo "Checking for remaining usage of 'List' as a type hint:" rg --type python "\bList\[" # Note: If these searches return results, consider updating those instances as well for consistency.Length of output: 400
Script:
#!/bin/bash # Description: Check for any remaining usage of typing.List in the codebase # Test: Search for any remaining imports of List from typing echo "Checking for remaining 'from typing import List' statements:" rg "from typing import .*List" --glob "*.py" # Test: Search for any remaining usage of 'List' as a type hint echo "Checking for remaining usage of 'List' as a type hint:" rg "\bList\[" --glob "*.py" # Note: If these searches return results, consider updating those instances as well for consistency.Length of output: 2688
package/PartSeg/common_gui/equal_column_layout.py (1)
Line range hint
1-78: Consider adding type hints to method parameters and return valuesWhile updating the type hint for
self._item_list, it would be beneficial to add type hints to method parameters and return values throughout the class. This would improve code clarity and maintain consistency with modern Python practices.For example:
def addItem(self, item: QLayoutItem) -> None:def setGeometry(self, rect: QRect) -> None:def itemAt(self, p_int: int) -> QLayoutItem | None:This is not directly related to dropping Python 3.8 support but would further modernize the codebase.
package/PartSegCore/image_transforming/interpolate_image.py (1)
35-35: Approved: Type hint update is consistent with modern Python practicesThe change from
Tuple[Image, Optional[ROIInfo]]totuple[Image, Optional[ROIInfo]]is appropriate and aligns with the PR objective. This update:
- Uses the built-in
tupletype for type hinting, which is preferred in Python 3.9+.- Maintains the same semantic meaning as the previous type hint.
- Is backwards compatible with Python 3.9+.
For consistency, consider updating the import statement at the top of the file to remove the unused
ListandTupleimports from thetypingmodule. This will clean up the imports and reflect the changes made in the type hints.package/PartSegCore/image_transforming/image_projection.py (1)
42-42: LGTM: Method signature update with minor suggestionThe update of the return type annotation from
Tuple[Image, Optional[ROIInfo]]totuple[Image, Optional[ROIInfo]]is correct and aligns with modern Python type hinting practices. This change maintains the same semantic meaning while using the built-in type, which is consistent with the PR objective.For consistency, consider updating the type hint for the
callback_functionparameter as well:- callback_function: Optional[Callable[[str, int], None]] = None, + callback_function: Callable[[str, int], None] | None = None,This change would use the
|syntax for union types, which is consistent with the use of built-in types for type hinting in Python 3.10+.package/PartSegCore/analysis/io_utils.py (2)
30-30: Approved: Updated type hint to use built-inlistThis change from
typing.Listtolistis consistent with modern Python type hinting practices for Python 3.9+. It improves code readability and aligns with the previous change.For consistency, consider updating other type hints in this file that still use the
typingmodule, such astyping.Optionalon lines 29 and 33. This would further streamline the code and fully adopt the new type hinting style.
Line range hint
1-78: Summary: Successful transition to modern type hintingThe changes in this file successfully update the type hints for
additional_layersandhistoryattributes in theProjectTupleclass. These modifications align with the PR objective of dropping Python 3.8 support and adopt a more modern approach to type hinting available in Python 3.9+.To further improve the codebase:
- Consider updating all remaining
typingmodule usages in this file to their built-in equivalents where applicable (e.g.,typing.Optionalto| None).- Review other files in the project for similar opportunities to modernize type hints.
These additional changes would ensure consistency across the codebase and fully leverage the benefits of modern Python type hinting.
package/PartSegImage/channel_class.py (2)
Line range hint
26-34: Approved: Pydantic 2 compatibility addedThe addition of a new
check_type_function for Pydantic 2 compatibility is a good approach:
- It ensures the code works with both Pydantic 1 and 2.
- The core type checking logic remains consistent.
Suggestion for improvement:
Consider adding a brief comment explaining the purpose of_validation_infoand**_parameters in the Pydantic 2 version for better code documentation.You could add a comment like this:
def check_type_(value, _validation_info=None, **_): # _validation_info and **_ are used for Pydantic 2 compatibility return check_type(value)
82-85: Approved: Added Pydantic 2 schema methodThe addition of the
__get_pydantic_json_schema__method is appropriate for Pydantic 2 compatibility. It correctly reuses the logic from__modify_schema__for consistency.However, there's an outstanding TODO comment in the
__modify_schema__method that should be addressed:# TODO check if still requiredPlease review if the
__modify_schema__method is still required for Pydantic 1 compatibility. If not, consider removing it and updating the__get_pydantic_json_schema__method accordingly.package/PartSeg/common_backend/partially_const_dict.py (1)
Line range hint
13-85: Consider enhancing type hints in class methods.While the changes made are correct and improve the overall type hinting, there's an opportunity to further enhance type safety within the
PartiallyConstDictclass methods. Consider the following suggestions:
- Add return type hints to methods like
__setitem__,__len__,__iter__, etc.- Use more specific types instead of
Anywhere possible, especially in method parameters and return values.- Consider using
TypedDictforconst_item_dictif its structure is known and consistent.Example improvements:
def __setitem__(self, key: str, value: Union[T, RemovableInfo]) -> None: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[str]: ... def get_position(self, key: str) -> int: ...These additional type hints would further improve code readability and catch potential type-related issues earlier in the development process.
package/PartSeg/plugins/modeling_save/save_modeling_data.py (2)
21-21: LGTM! Consider further simplifying the type hint.The change from
typing.Listtolistis a good modernization step, aligning with Python 3.9+ practices and improving readability. This change is consistent with dropping Python 3.8 support.Consider further simplifying the type hint by using
|instead oftyping.Unionfor Python 3.10+:def get_fields(cls) -> list[AlgorithmProperty | str]:This change would make the type hint even more concise and readable, assuming the project now targets Python 3.10 or later.
Line range hint
1-91: Consider additional improvements for consistency and maintainability.While the current change is good, there are a few more areas that could be improved:
Type hints: Consider updating other type hints in the file for consistency. For example, in the
savemethod signature,typing.Unioncould be replaced with|for Python 3.10+.Method complexity: The
savemethod is quite long and handles multiple responsibilities. Consider refactoring it into smaller, more focused methods to improve readability and maintainability.Error handling: The
savemethod raises anOSErrorwith a custom message. Consider using a more specific exception type or creating a custom exception for this case.Would you like assistance in implementing any of these suggestions?
package/PartSeg/plugins/napari_widgets/colormap_control.py (1)
Line range hint
1-48: Recommendation: Update project documentation for minimum Python version.Given that this PR is part of dropping support for Python 3.8 and the type hint changes are compatible with Python 3.9+, it's important to ensure that the project's documentation (README, setup.py, etc.) clearly states the new minimum supported Python version. This will help users and contributors understand the compatibility requirements of the project.
package/PartSeg/plugins/old_partseg/old_partseg.py (1)
Line range hint
1-90: Consider updating other type hints for consistencyWhile this change updates the type hint for
load_locations, there are other instances of type hints in the file that could be modernized for consistency. For example,typing.Optionalandtyping.Callableare still used. Consider updating these as well to use the newer syntax introduced in Python 3.9+.Would you like assistance in identifying and updating the remaining type hints in this file?
package/PartSeg/_roi_mask/segmentation_info_dialog.py (1)
48-48: LGTM: Method signature updated correctlyThe change from
Dicttodictin the method signature is consistent with the PR objective and the import statement update. The functionality remains the same, and the type hint has been correctly modernized.For future compatibility, consider using
| Noneinstead ofOptionalif targeting Python 3.10+:def set_parameters_dict(self, val: dict[int, ROIExtractionProfile] | None):This syntax is more concise and aligns with newer Python type hinting practices.
package/PartSeg/_launcher/check_version.py (1)
43-45: Approve changes with a minor suggestion.The refactoring of the context managers improves code readability while maintaining the same functionality. Good job on combining the file opening and error suppression into a single
withstatement.A minor suggestion to further improve the code:
Consider using a
pathlib.Pathobject for file path operations. This can make the code more readable and platform-independent. Here's how you could modify the relevant lines:-if os.path.exists(os.path.join(state_store.save_folder, IGNORE_FILE)): - with ( - open(os.path.join(state_store.save_folder, IGNORE_FILE), encoding="utf-8") as f_p, +from pathlib import Path + +ignore_file_path = Path(state_store.save_folder) / IGNORE_FILE +if ignore_file_path.exists(): + with ( + ignore_file_path.open(encoding="utf-8") as f_p, suppress(ValueError), ): # ... rest of the code ... - os.remove(os.path.join(state_store.save_folder, IGNORE_FILE)) + ignore_file_path.unlink()This change would make the code more Pythonic and easier to maintain across different operating systems.
package/PartSegCore/roi_info.py (1)
80-80: LGTM: Type hint update incalc_boundsmethod, but docstring needs adjustment.The change from
Dict[int, BoundInfo]todict[int, BoundInfo]in the return type hint is consistent with the other updates in the file and aligns with modern Python practices.However, the method's docstring still mentions the return type as
Dict[int, BoundInfo]. Please update the docstring to maintain consistency:@staticmethod def calc_bounds(roi: np.ndarray) -> dict[int, BoundInfo]: """ Calculate bounding boxes components :param np.ndarray roi: array for which bounds boxes should be calculated :return: mapping component number to bounding box - :rtype: Dict[int, BoundInfo] + :rtype: dict[int, BoundInfo] """package/PartSegCore/image_operations.py (2)
82-82: Approved: Type annotation update inmedianfunctionThe change from
List[int]tolist[int]in the type annotation for theradiusparameter is appropriate. It aligns with modern Python type hinting practices and is consistent with dropping support for Python 3.8.Consider updating the docstring to reflect the new type annotation:
def median(image: np.ndarray, radius: Union[int, list[int]], layer=True): """ Median blur of image. :param np.ndarray image: image to apply median filter :param Union[int, list[int]] radius: radius for median kernel (single int or list of ints) :param bool layer: if operation should be run on each layer separately :return: Blurred image :rtype: np.ndarray """This change would improve the documentation and make it consistent with the updated type annotation.
Line range hint
1-150: Overall assessment: Changes align with PR objectivesThe modifications in this file, including the updated import statement and type annotation, are consistent with the PR objective of dropping support for Python 3.8. These changes improve code quality by adopting more modern Python practices without altering the functionality of the image processing operations.
Consider applying similar type annotation updates throughout the codebase for consistency. This will help maintain a uniform coding style and leverage the latest Python type hinting features.
package/PartSegCore/project_info.py (1)
118-118: Update docstring to match the new type hintThe change from
Optional[List[int]]toOptional[list[int]]for thecomponentsparameter is appropriate and consistent with the transition to using built-in types. This maintains the same semantic meaning while improving compatibility with newer Python versions.However, the docstring for this function still mentions
List[int]in the parameter description. For consistency, please update the docstring as well.Update the docstring as follows:
- :param Optional[List[int]] components: If present inform which components + :param Optional[list[int]] components: If present inform which components should be used when calculation mask, otherwise use all.package/PartSeg/_roi_mask/batch_proceed.py (1)
43-43: LGTM! Consider using|for union types.The change from
Listtolistin the type hint for thetaskparameter is consistent with the move to use built-in types for type hinting in Python 3.9+. This change maintains the same meaning while updating the syntax.For further improvement and consistency with modern Python type hinting (Python 3.10+), consider using the
|operator for union types:- def add_task(self, task: Union[BatchTask, list[BatchTask]]): + def add_task(self, task: BatchTask | list[BatchTask]):This change would make the type hint more concise and align with the latest Python type hinting practices.
package/PartSegImage/image_writer.py (1)
Line range hint
1-1: Overall changes align with PR objectiveThe changes in this file are consistent with the PR objective of dropping Python 3.8 support. The updates to type hints, using
dictinstead oftyping.Dict, leverage features available in Python 3.9+. These changes improve code readability without altering the functionality of theIMAGEJImageWriterclass.However, it's worth noting that similar updates could potentially be applied to other parts of the file, such as the
ImageWriterclass, to maintain consistency across the codebase.Consider reviewing the rest of the file and other files in the project for similar opportunities to update type hints, ensuring consistency throughout the codebase.
package/PartSeg/common_backend/base_argparser.py (2)
Line range hint
80-91: LGTM: Argument definitions improved, with a minor suggestion.The changes to
--save_suffixand--save_directoryarguments are good improvements:
- Using
default=[...]ensures consistency withnargs=1.- The updated help text for
--save_directoryprovides clearer information about customization options.Consider adding quotes around the environment variable name for better readability:
- "Could be customized using 'PARTSEG_SETTINGS_DIR' environment variable.", + "Could be customized using 'PARTSEG_SETTINGS_DIR' environment variable.",
Line range hint
132-134: LGTM: Improved Sentry SDK version compatibility.The addition of version-specific kwargs for Sentry initialization is a good improvement:
- It allows setting
max_value_lengthon newer Sentry SDK versions without breaking compatibility with older versions.- The use of the
SENTRY_GE_1_29constant provides clear version checking.For improved clarity, consider adding a brief comment explaining the version-specific behavior:
init_kwargs = {"release": f"PartSeg@{__version__}"} if SENTRY_GE_1_29: # Set max_value_length for Sentry SDK versions >= 1.29.0 init_kwargs["max_value_length"] = 10**4azure-pipelines.yml (2)
Line range hint
1-200: Consider standardizing Python versions across stagesWhile the changes made align with dropping Python 3.8 support, there's an inconsistency in Python versions across different stages:
- manifest_check uses Python 3.10
- Documentation_check and Notebook_check use Python 3.11
- The sdist job in the Builds stage doesn't specify a Python version
Consider standardizing these to use the same Python version (preferably 3.11) across all stages for consistency and to simplify maintenance.
Also, it's recommended to specify a Python version for the sdist job in the Builds stage to ensure reproducibility.
Here's a suggested change for the sdist job:
- job: sdist pool: {vmImage: 'Ubuntu-22.04'} steps: - - task: UsePythonVersion@0 + - task: UsePythonVersion@0 + inputs: + versionSpec: '3.11' + architecture: x64 - bash: pip install -r requirements/requirements_dev.txt displayName: sdist requirements
Line range hint
1-200: Summary of Azure Pipelines configuration changesThe changes made to
azure-pipelines.ymlsuccessfully remove Python 3.8 from the CI/CD pipeline, aligning with the PR objective. However, there are a few points to consider for further improvement:
- Standardize Python versions: Consider using Python 3.11 across all stages for consistency.
- Verify compatibility: Ensure all tools and scripts are compatible with the updated Python versions.
- Specify Python version for sdist job: Add a specific Python version to the sdist job in the Builds stage.
These changes will enhance the maintainability and reliability of your CI/CD pipeline. Once these suggestions are addressed, the pipeline configuration will be well-aligned with the goal of dropping Python 3.8 support.
.github/workflows/tests.yml (2)
137-138: LGTM: Minimal test updated to Python 3.9.The
test_minimaljob has been correctly updated to use Python 3.9 instead of 3.8, which is consistent with dropping support for Python 3.8. The tox environment has also been updated accordingly.Consider using a variable for the Python version in the
tox_argsto make future updates easier. For example:with: test_data: True python_version: "3.9" tox_args: "-e py${{ matrix.python_version.replace('.', '') }}-PyQt5-minimal" coverage: trueThis way, you only need to update the
python_versionfield in the future, and thetox_argswill automatically adjust.
Line range hint
1-265: Summary: Successfully dropped Python 3.8 support in the test workflow.The changes in this file consistently remove Python 3.8 from the test matrix across all relevant jobs (
base-test,base-test-main, andtest_minimal). The workflow now tests against Python versions 3.9 through 3.12, which aligns with the PR objective of dropping Python 3.8 support and keeps the project up-to-date with the latest Python releases.These changes ensure that the CI pipeline will no longer test against the unsupported Python 3.8 version, reducing maintenance overhead and focusing on supported Python versions.
To further improve the workflow's maintainability, consider:
- Using GitHub Actions'
strategy.matrixfeature to define Python versions in one place and reuse them across jobs.- Implementing a centralized configuration for minimum and maximum supported Python versions, which can be referenced throughout the workflow.
These suggestions could make future Python version updates even easier to manage.
package/PartSeg/_roi_analysis/partseg_settings.py (3)
145-145: LGTM with a suggestion: Updated return type hint forsegmentation_pipelinesThe change from
typing.Dict[str, SegmentationPipeline]todict[str, SegmentationPipeline]is correct and consistent with the modernization of type hints in this PR.However, it's worth noting that this property is marked as deprecated. While maintaining backwards compatibility is important, consider creating a plan to remove this deprecated property in a future release to reduce technical debt.
Would you like assistance in creating a deprecation plan or timeline for removing this property?
150-150: LGTM with a suggestion: Updated return type hints for multiple propertiesThe changes from
typing.Dict[str, ...]todict[str, ...]forroi_pipelines,segmentation_profiles,roi_profiles,batch_plans, andmeasurement_profilesare correct and consistent with the modernization of type hints in this PR.Similar to the
segmentation_pipelinesproperty,segmentation_profilesis marked as deprecated. Consider creating a deprecation plan for both these properties to ensure they are removed in a future release, reducing technical debt.Would you like assistance in creating a unified deprecation plan for both
segmentation_pipelinesandsegmentation_profiles?Also applies to: 154-154, 159-159, 163-163, 167-167
Line range hint
34-167: Summary: Successful modernization of type hints with a suggestion for future workThe changes in this file successfully update type hints from
typing.Listandtyping.Dicttolistanddict, aligning with Python 3.9+ practices. This is consistent with the PR objective of dropping Python 3.8 support and improves code readability.For future work, consider creating a task to address the deprecated
segmentation_pipelinesandsegmentation_profilesproperties. This could involve:
- Setting a timeline for removal
- Updating any code that still relies on these properties
- Providing clear migration paths for users of these properties
This will help reduce technical debt and keep the codebase clean.
Would you like assistance in creating a GitHub issue to track the deprecation and removal of these properties?
package/PartSeg/common_gui/napari_viewer_wrap.py (1)
Line range hint
36-39: LGTM: Enhanced widget interactivity.The new connections between checkboxes and buttons improve the user interface by disabling buttons when their corresponding checkboxes are checked. This prevents redundant actions and enhances the overall user experience.
Consider extracting this pattern into a helper method to improve code readability and maintainability. For example:
def connect_checkbox_to_button(checkbox: QCheckBox, button: QPushButton): checkbox.stateChanged.connect(button.setDisabled) # Usage connect_checkbox_to_button(self.sync_image_chk, self.sync_image_btn) connect_checkbox_to_button(self.sync_ROI_chk, self.sync_ROI_btn) connect_checkbox_to_button(self.sync_additional_chk, self.sync_additional_btn) connect_checkbox_to_button(self.sync_points_chk, self.sync_points_btn)This approach would make the code more DRY and easier to maintain.
package/PartSegCore/analysis/batch_processing/parallel_backend.py (1)
262-262: LGTM with a minor observation: Updated type hint, but inconsistent with BatchWorkerThe change from
Dict[uuid.UUID, Any]todict[uuid.UUID, Any]for thecalculation_dictparameter is good, adopting the modern built-in type for generics. However, there's an inconsistency with the type hint used in theBatchWorkerconstructor for the same parameter, which is more specific:dict[uuid.UUID, tuple[Any, Callable[[Any, Any], Any]]].Consider updating this type hint to match the one in the
BatchWorkerconstructor for consistency:def spawn_worker(task_queue: Queue, order_queue: Queue, result_queue: Queue, calculation_dict: dict[uuid.UUID, tuple[Any, Callable[[Any, Any], Any]]]):This will ensure type consistency across the codebase and provide more precise type information.
package/PartSeg/common_gui/advanced_tabs.py (1)
239-239: LGTM: Updated type hint and added docstring improve code quality.The changes in this segment are beneficial:
- The type hint update from
List[str]tolist[str]is consistent with the previous change and aligns with modern Python practices.- The addition of a docstring improves the documentation of the
AdvancedWindowclass.Consider expanding the docstring to include information about all parameters, not just
settingsandimage_view_names. For example:def __init__(self, settings: BaseSettings, image_view_names: list[str], reload_list=None, parent=None): """ Initialize the AdvancedWindow. :param settings: Program settings :param image_view_names: List of image view names to be passed to PColormapList :param reload_list: Optional list of functions to be called on reload (default: None) :param parent: Parent widget (default: None) """package/PartSegCore/analysis/save_functions.py (1)
401-401: LGTM: Updated return type hint for Python 3.9+ compatibility.The change from
typing.List[typing.Union[AlgorithmProperty, str]]tolist[typing.Union[AlgorithmProperty, str]]is consistent with the PR objective of dropping Python 3.8 support. This update improves readability by using the built-inlisttype.For future consideration: If the project plans to support Python 3.10+, you could further simplify this type hint by using the
|operator for union types:def get_fields(cls) -> list[AlgorithmProperty | str]: return []This would make the type hint even more concise and readable.
package/PartSeg/_roi_mask/stack_settings.py (1)
Line range hint
320-337: LGTM: Updated parameter type annotation forget_maskfunction, but docstring needs updateThe change from
typing.List[int]tolist[int]as the type annotation for theselectedparameter is correct and aligns with the goal of using built-in type annotations available in Python 3.9+. This update maintains the same functionality while modernizing the type hinting.However, there's a minor inconsistency:
The docstring still mentions
typing.List[int]for theselectedparameter. Please update it to match the new type annotation:- :param typing.List[int] selected: list of selected components which should be masked as non segmentation area + :param list[int] selected: list of selected components which should be masked as non segmentation areapackage/PartSeg/plugins/napari_widgets/roi_extraction_algorithms.py (2)
86-87: LGTM: Improved type hinting, consider adding test coverageThe update from
typing.Type[AlgorithmSelection]totype[AlgorithmSelection]aligns with modern Python type hinting practices (PEP 585). This change enhances readability and ensures forward compatibility with Python 3.9+, while maintaining the same functionality.Additionally, consider adding test coverage for this method, as it's currently marked with
# pragma: no cover.
Line range hint
1-404: Overall: Excellent type hint updates, consider updating minimum Python versionThe changes in this file consistently update type hints to use built-in types instead of the
typingmodule, aligning with PEP 585 and modern Python practices. These updates improve code readability and ensure forward compatibility with Python 3.9+, which is in line with the PR objective of dropping support for Python 3.8.To fully leverage these changes and maintain consistency across the project, consider updating the minimum required Python version to 3.9 in your project's configuration files (e.g.,
setup.py,pyproject.toml, orrequirements.txt).package/PartSeg/common_gui/multiple_file_widget.py (1)
Line range hint
1-376: Summary: Consistent type hint modernizationThe changes in this file focus on updating type hints to use the more modern syntax introduced in PEP 585. These updates improve code readability and maintainability without altering the functionality. Great job on maintaining consistency throughout the file!
Suggestion for future improvement:
Consider updating the entire codebase to use this modern type hinting syntax for consistency. This could be done as a separate task or gradually as files are modified.package/tests/test_PartSeg/test_channel_control.py (3)
255-258: Systematic improvement in signal waiting logic across multiple test casesThe consistent application of consolidating multiple
qtbot.waitSignalcalls into singlewithstatements across various test cases is commendable. This systematic refactoring enhances code readability and maintainability while preserving the original functionality.Consider creating a helper function to further reduce code duplication, especially if this pattern is used extensively throughout the test suite. For example:
def wait_for_signals(qtbot, *signals): return qtbot.waitSignals(signals) # Usage with wait_for_signals(qtbot, box.coloring_update, box.change_channel): # Test actionThis approach could make the tests even more concise and easier to maintain.
Also applies to: 261-264, 267-270, 273-276, 280-283, 286-289
336-339: Comprehensive application of improved signal waiting logicThe consistent application of the consolidated signal waiting pattern across multiple test cases in the
test_image_view_integrationmethod is excellent. This systematic approach to refactoring enhances code readability and maintainability throughout the test suite.Given the widespread use of this pattern, I'd like to reiterate the suggestion for creating a helper function to further reduce code duplication:
def wait_for_signals(qtbot, *signals): return qtbot.waitSignals(signals) # Usage with wait_for_signals(qtbot, image_view.channel_control.coloring_update, image_view.channel_control.change_channel): # Test actionImplementing this helper function could significantly streamline the test code and make future modifications easier.
Also applies to: 344-347, 353-356, 363-366, 374-377, 384-387
406-409: Consistent signal waiting logic improvement in Gaussian filter testThe application of the consolidated signal waiting pattern in the
test_image_view_integration_gaussmethod maintains the consistency seen throughout the file. This systematic refactoring approach significantly enhances the overall readability and maintainability of the test suite.The repeated use of this pattern across multiple test methods further emphasizes the potential benefits of implementing the previously suggested helper function. Such a function would not only reduce code duplication but also make the tests more concise and easier to modify in the future.
Also applies to: 413-416, 422-425, 432-435
package/PartSeg/_roi_analysis/export_batch.py (1)
Line range hint
466-480: Approved: Enhanced flexibility withzenodo_urlparameterThe addition of the
zenodo_urlparameter with a default value is a positive change that:
- Increases the function's flexibility by allowing users to specify different Zenodo API URLs.
- Maintains backward compatibility through the default value.
- Facilitates easier testing and use of different Zenodo environments (e.g., sandbox).
This change aligns well with the function's purpose and improves its versatility.
Consider adding a brief comment above the function to explain the purpose of the
zenodo_urlparameter, e.g.:def export_to_zenodo( excel_path: Path, base_folder: Path, zenodo_token: str, title: str, author: str, affiliation: str, orcid: str, description: str, zenodo_url: str = "https://zenodo.org/api/deposit/depositions", ): """ Export project to Zenodo :param zenodo_url: Zenodo API URL. Use a different URL for sandbox or testing environments. ... """This would provide clarity for future developers or users of this function.
package/PartSeg/_roi_analysis/batch_window.py (2)
379-381: LGTM! Consider updating other type hints for consistency.The change from
typing.Listtolistin thefile_listparameter type annotation is a positive update, consistent with modern Python practices. To maintain consistency throughout the codebase:Consider updating other type hints in this file and across the project to use built-in types where applicable. For example:
- def __init__( - self, - file_list: list[os.PathLike], - calculation_plan: CalculationPlan, - measurement_file_path: os.PathLike, - settings: PartSettings, - batch_manager: CalculationManager, - parent: typing.Optional[QWidget] = None, - ): + def __init__( + self, + file_list: list[os.PathLike], + calculation_plan: CalculationPlan, + measurement_file_path: os.PathLike, + settings: PartSettings, + batch_manager: CalculationManager, + parent: QWidget | None = None, + ):This change replaces
typing.Optional[QWidget]withQWidget | None, which is the preferred syntax for optional types in modern Python.
Line range hint
1-638: Consider a project-wide update of type hintsThe changes in this file are positive steps towards modernizing the codebase and aligning with current Python best practices. To further improve the project:
- Conduct a project-wide search for usage of
typing.List,typing.Dict,typing.Optional, and other similar type hints from thetypingmodule.- Replace them with their built-in equivalents (
list,dict,| None, etc.) where appropriate.- Update the project's style guide or contribution guidelines to reflect this new approach to type hinting.
This comprehensive update will ensure consistency across the entire codebase and fully leverage the benefits of modern Python type hinting.
To assist with this project-wide update, you could use a tool like
pyupgradeor create a custom script. Here's an example of how you might search for these patterns:#!/bin/bash # Search for typing.List, typing.Dict, and typing.Optional usage echo "Searching for typing.List usage:" rg "typing\.List" --type python echo "\nSearching for typing.Dict usage:" rg "typing\.Dict" --type python echo "\nSearching for typing.Optional usage:" rg "typing\.Optional" --type pythonThis script will help identify areas of the codebase that may need updating to align with the new type hinting approach.
package/PartSegCore/analysis/calculation_plan.py (1)
Line range hint
1-824: Overall good changes, with some suggestions for future improvementsThe updates to type annotations throughout the file are good improvements that enhance code readability and follow modern Python practices. However, there are a few areas that could be addressed in future updates:
There's a TODO comment on line 4 about adding tests. It would be beneficial to address this and ensure proper test coverage for the code.
The
CalculationPlanclass is quite large and complex. Consider breaking it down into smaller, more focused classes or modules to improve maintainability.Some methods in the
CalculationPlanclass, likeget_el_name, use long if-elif chains. Consider refactoring these to use a dictionary-based approach or a separate dispatcher class to improve readability and maintainability.The error handling in some methods (e.g.,
dict_load) could be improved by using more specific exception types and providing more informative error messages.Consider adding more type annotations to method parameters and return values throughout the file for consistency and improved type checking.
These suggestions aim to improve the overall structure, maintainability, and robustness of the code. Implementing them gradually in future updates would be beneficial for the long-term health of the project.
package/PartSeg/common_gui/channel_control.py (1)
627-628: Type hint updates are correct, but could be further improved.The return type hint for the
get_limitsmethod and the type hint for therespvariable have been updated to uselistandtupleinstead oftyping.Listandtyping.Tuple. This is consistent with previous changes.However, the use of
typing.Unioncould be further modernized if the project's minimum supported Python version is 3.10 or later.If the minimum supported Python version is 3.10 or later, consider updating the union type hint to use the
|operator:def get_limits(self) -> list[tuple[int, int] | None]: resp: list[tuple[int, int] | None] = [(0, 0)] * self.layout().count() # ... rest of the methodThis change would make the type hints even more concise and aligned with modern Python practices.
package/PartSegImage/image.py (3)
Line range hint
32-35: LGTM: Updated type annotations in ChannelInfo and ChannelInfoFull classes.The changes to
color_mapandcontrast_limitsattributes in bothChannelInfoandChannelInfoFullclasses are good improvements:
- The use of the new union type syntax (
|) makes the type hints more readable and concise.- These changes are consistent with modern Python type hinting practices.
Consider using
typing.Literalfor the string color map options to provide even more precise type hinting. For example:from typing import Literal ColorMapStr = Literal["red", "green", "blue", "yellow", "cyan", "magenta"] class ChannelInfo: color_map: ColorMapStr | np.ndarray | tuple | list | None = NoneThis would provide better type checking for string color map values.
Also applies to: 40-43
Line range hint
201-214: LGTM: Updated type annotations in Image class init method.The changes to the
__init__method of theImageclass are good improvements:
- The type hints for
data,spacing, andchannel_infoparameters have been updated to use the new type aliases and syntax.- These changes are consistent with the updates made earlier in the file and improve type safety.
For consistency, consider updating the type hint for the
maskparameter to use the new union syntax:mask: None | np.ndarray = NoneThis would make it consistent with the style used in other parts of the file.
Line range hint
1-1000: Overall assessment: Type hint updates improve code quality and maintainability.The changes made to this file are focused on updating type hints to use more modern Python syntax. These improvements include:
- Updating type aliases to use built-in types instead of those from the
typingmodule.- Using the new union type syntax (
|) in various class attributes and method parameters.- Improving the specificity of type hints in method signatures and return types.
These changes align well with the PR objective of dropping Python 3.8 support and adopting more recent Python features. They improve code readability, maintainability, and type safety without altering the underlying functionality.
Consider adding a note in the module docstring or README file specifying the minimum Python version required (3.10+) due to the use of new type hinting features. This will help future contributors and users understand the compatibility requirements of this module.
package/PartSegCore/analysis/batch_processing/batch_backend.py (4)
Line range hint
224-226: Consider updating type hints in CalculationProcess class.While the CalculationProcess class implementation remains unchanged, for consistency with the rest of the file, consider updating type hints within this class as well. For example, you could add return type hints to methods and use built-in types for annotations where applicable.
Line range hint
590-592: Consider enhancing error handling and type hinting in FileData class.The FileData class handles critical file writing operations. While the implementation is solid, consider the following improvements:
- Add more specific exception handling in methods like
wrote_data_to_file.- Update type hints throughout the class for consistency with the rest of the file.
- Consider adding logging for better traceability of file operations.
Line range hint
824-826: Enhance DataWriter class with improved documentation and type hints.The DataWriter class plays a crucial role in managing multiple FileData instances. Consider the following improvements:
- Add more detailed docstrings to methods, explaining their purpose and parameters.
- Update type hints throughout the class for consistency with the rest of the file.
- Consider adding runtime type checking for critical parameters to enhance robustness.
Line range hint
1-858: Overall good progress, consider extending improvements.The updates to type hints in this file are a positive step towards more modern Python practices. To further improve the code:
- Extend the type hint updates throughout the entire file for consistency.
- Enhance documentation, especially for complex methods and classes.
- Consider adding more comprehensive error handling and logging.
- Review the file for any potential performance optimizations, especially in file writing operations.
These changes will contribute to better maintainability and robustness of the codebase.
package/PartSeg/_roi_analysis/advanced_window.py (2)
844-844: LGTM: Updated type hint to use built-in genericsThe type hint for
objects_listhas been updated to use built-inlistandtupletypes instead ofListandTuplefrom thetypingmodule. This change is consistent with PEP 585 and modern Python typing practices.Consider using the
|operator for union types if you're using Python 3.10+. This would make the type hint more concise:objects_list: Optional[list[tuple[str, _DialogType] | tuple[str, _DialogType, str]]] = None
Line range hint
1-944: Summary: Type hint modernizationThe changes in this file focus on updating type hints to use built-in generics (e.g.,
list,tuple) instead of theirtypingmodule counterparts (e.g.,List,Tuple). These updates align with PEP 585 and represent a move towards more modern Python typing practices. The changes are consistent throughout the file and should not affect the runtime behavior of the code.Key benefits of these changes include:
- Reduced dependency on the
typingmodule- Improved readability for developers familiar with newer Python versions
- Preparation for potential future removal of older typing syntax
Consider updating the project's minimum Python version requirement to 3.9+ in the project metadata, as these changes are most beneficial for Python 3.9 and later. This would allow for consistent use of these modern typing features across the entire project.
package/PartSegCore/mask_create.py (1)
Line range hint
37-43: Fix incorrect attribute names in__eq__methodIn the
__eq__method ofMaskProperty, the attributesother.clip_maskandother.reverse_maskare incorrect. The correct attribute names areother.clip_to_maskandother.reversed_mask. This typo may cause incorrect equality comparisons betweenMaskPropertyinstances.Please apply the following diff to correct the attribute names:
def __eq__(self, other): return ( isinstance(other, MaskProperty) and self.dilate == other.dilate and self.dilate_radius == other.dilate_radius and self.fill_holes == other.fill_holes and self.max_holes_size == other.max_holes_size - and self.clip_to_mask == other.clip_mask - and self.reversed_mask == other.reverse_mask + and self.clip_to_mask == other.clip_to_mask + and self.reversed_mask == other.reversed_mask )package/PartSeg/common_gui/algorithms_description.py (1)
398-399: Consider importingUniondirectly for cleaner type hintsInstead of using
typing.Unionin type annotations, consider importingUniondirectly fromtypingfor improved readability. This change simplifies the annotations and makes the code cleaner.Apply this change to the import statements:
+from typing import UnionAnd update the type hint:
-self.channels_chose: list[typing.Union[ChannelComboBox, SubAlgorithmWidget]] = [] +self.channels_chose: list[Union[ChannelComboBox, SubAlgorithmWidget]] = []
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (82)
- .github/workflows/tests.yml (3 hunks)
- .pre-commit-config.yaml (1 hunks)
- azure-pipelines.yml (2 hunks)
- package/PartSeg/_launcher/check_version.py (1 hunks)
- package/PartSeg/_launcher/main_window.py (2 hunks)
- package/PartSeg/_roi_analysis/advanced_window.py (4 hunks)
- package/PartSeg/_roi_analysis/batch_window.py (2 hunks)
- package/PartSeg/_roi_analysis/export_batch.py (1 hunks)
- package/PartSeg/_roi_analysis/main_window.py (1 hunks)
- package/PartSeg/_roi_analysis/measurement_widget.py (3 hunks)
- package/PartSeg/_roi_analysis/partseg_settings.py (3 hunks)
- package/PartSeg/_roi_analysis/prepare_plan_widget.py (4 hunks)
- package/PartSeg/_roi_analysis/profile_export.py (1 hunks)
- package/PartSeg/_roi_mask/batch_proceed.py (3 hunks)
- package/PartSeg/_roi_mask/main_window.py (1 hunks)
- package/PartSeg/_roi_mask/segmentation_info_dialog.py (2 hunks)
- package/PartSeg/_roi_mask/stack_settings.py (6 hunks)
- package/PartSeg/common_backend/base_argparser.py (1 hunks)
- package/PartSeg/common_backend/base_settings.py (11 hunks)
- package/PartSeg/common_backend/partially_const_dict.py (2 hunks)
- package/PartSeg/common_gui/advanced_tabs.py (2 hunks)
- package/PartSeg/common_gui/algorithms_description.py (10 hunks)
- package/PartSeg/common_gui/channel_control.py (11 hunks)
- package/PartSeg/common_gui/colormap_creator.py (8 hunks)
- package/PartSeg/common_gui/custom_load_dialog.py (4 hunks)
- package/PartSeg/common_gui/custom_save_dialog.py (2 hunks)
- package/PartSeg/common_gui/equal_column_layout.py (1 hunks)
- package/PartSeg/common_gui/error_report.py (2 hunks)
- package/PartSeg/common_gui/image_adjustment.py (2 hunks)
- package/PartSeg/common_gui/label_create.py (5 hunks)
- package/PartSeg/common_gui/main_window.py (5 hunks)
- package/PartSeg/common_gui/mask_widget.py (2 hunks)
- package/PartSeg/common_gui/multiple_file_widget.py (3 hunks)
- package/PartSeg/common_gui/napari_image_view.py (8 hunks)
- package/PartSeg/common_gui/napari_viewer_wrap.py (2 hunks)
- package/PartSeg/common_gui/numpy_qimage.py (1 hunks)
- package/PartSeg/common_gui/select_multiple_files.py (1 hunks)
- package/PartSeg/common_gui/stack_image_view.py (2 hunks)
- package/PartSeg/common_gui/universal_gui_part.py (2 hunks)
- package/PartSeg/plugins/modeling_save/save_modeling_data.py (1 hunks)
- package/PartSeg/plugins/napari_widgets/algorithm_widgets.py (2 hunks)
- package/PartSeg/plugins/napari_widgets/colormap_control.py (2 hunks)
- package/PartSeg/plugins/napari_widgets/lables_control.py (3 hunks)
- package/PartSeg/plugins/napari_widgets/roi_extraction_algorithms.py (5 hunks)
- package/PartSeg/plugins/napari_widgets/utils.py (1 hunks)
- package/PartSeg/plugins/old_partseg/old_partseg.py (1 hunks)
- package/PartSegCore/algorithm_describe_base.py (12 hunks)
- package/PartSegCore/analysis/analysis_utils.py (1 hunks)
- package/PartSegCore/analysis/batch_processing/batch_backend.py (2 hunks)
- package/PartSegCore/analysis/batch_processing/parallel_backend.py (5 hunks)
- package/PartSegCore/analysis/calculate_pipeline.py (2 hunks)
- package/PartSegCore/analysis/calculation_plan.py (5 hunks)
- package/PartSegCore/analysis/io_utils.py (1 hunks)
- package/PartSegCore/analysis/load_functions.py (9 hunks)
- package/PartSegCore/analysis/measurement_base.py (11 hunks)
- package/PartSegCore/analysis/measurement_calculation.py (18 hunks)
- package/PartSegCore/analysis/save_functions.py (2 hunks)
- package/PartSegCore/class_generator.py (1 hunks)
- package/PartSegCore/custom_name_generate.py (1 hunks)
- package/PartSegCore/image_operations.py (2 hunks)
- package/PartSegCore/image_transforming/combine_channels.py (3 hunks)
- package/PartSegCore/image_transforming/image_projection.py (2 hunks)
- package/PartSegCore/image_transforming/interpolate_image.py (3 hunks)
- package/PartSegCore/image_transforming/swap_time_stack.py (2 hunks)
- package/PartSegCore/image_transforming/transform_base.py (2 hunks)
- package/PartSegCore/io_utils.py (14 hunks)
- package/PartSegCore/mask/io_functions.py (11 hunks)
- package/PartSegCore/mask_create.py (5 hunks)
- package/PartSegCore/napari_plugins/loader.py (2 hunks)
- package/PartSegCore/napari_plugins/save_tiff_layer.py (2 hunks)
- package/PartSegCore/project_info.py (5 hunks)
- package/PartSegCore/register.py (1 hunks)
- package/PartSegCore/roi_info.py (4 hunks)
- package/PartSegCore/segmentation/algorithm_base.py (3 hunks)
- package/PartSegCore/segmentation/restartable_segmentation_algorithms.py (3 hunks)
- package/PartSegCore/sphinx/auto_parameters.py (2 hunks)
- package/PartSegCore/utils.py (2 hunks)
- package/PartSegImage/channel_class.py (2 hunks)
- package/PartSegImage/image.py (1 hunks)
- package/PartSegImage/image_reader.py (7 hunks)
- package/PartSegImage/image_writer.py (2 hunks)
- package/tests/test_PartSeg/test_channel_control.py (5 hunks)
⛔ Files not processed due to max files limit (10)
- package/tests/test_PartSeg/test_common_backend.py
- package/tests/test_PartSeg/test_common_gui.py
- package/tests/test_PartSegCore/segmentation/test_segmentation_algorithm.py
- package/tests/test_PartSegCore/test_algorithm_describe_base.py
- package/tests/test_PartSegCore/test_class_generator.py
- package/tests/test_PartSegCore/test_class_register.py
- package/tests/test_PartSegCore/test_io.py
- package/tests/test_PartSegCore/test_segmentation.py
- pyproject.toml
- tox.ini
✅ Files skipped from review due to trivial changes (2)
- package/PartSeg/_roi_analysis/main_window.py
- package/PartSeg/plugins/napari_widgets/algorithm_widgets.py
🧰 Additional context used
🔇 Additional comments (287)
package/PartSegCore/custom_name_generate.py (2)
3-3: LGTM: Import statement updated correctly.The import statement has been appropriately updated to only import
Anyfrom thetypingmodule. This change is consistent with the use of built-in generics (setanddict) in the function signature, which aligns with the PR objective of dropping support for Python 3.8.
6-6: LGTM: Function signature updated correctly.The function signature has been appropriately updated to use built-in generics (
setanddict) instead oftyping.Setandtyping.Dict. This change is in line with the PR objective of dropping support for Python 3.8 and adopting features available in Python 3.9+. The type information remains consistent, ensuring the function's interface is unchanged.package/PartSegCore/image_transforming/transform_base.py (3)
17-17: LGTM: Improved type hinting for Python 3.9+The change from
Tupletotuplein the return type annotation aligns with PEP 585, which allows using built-in collection types in annotations. This syntax is supported in Python 3.9+, improving readability and following modern Python type hinting practices. The change is consistent with the PR objective of dropping Python 3.8 support.
21-21: LGTM: Improved type hinting for Python 3.9+The change from
Listtolistin the return type annotation aligns with PEP 585, which allows using built-in collection types in annotations. This syntax is supported in Python 3.9+, improving readability and following modern Python type hinting practices. The change is consistent with the PR objective of dropping Python 3.8 support. TheUniontype remains capitalized, which is correct as it's imported from thetypingmodule.
Line range hint
1-28: Overall LGTM: Successfully updated type hints for Python 3.9+The changes in this file successfully update the type hints to be compatible with Python 3.9+, which is consistent with the PR objective of dropping Python 3.8 support. The updates improve code readability and follow modern Python practices.
As a follow-up action, ensure that the project's documentation, setup files, and CI/CD configurations are updated to reflect the new minimum Python version requirement.
To verify that the minimum Python version has been updated in the project documentation and configuration files, you can run the following script:
Please review the output to ensure that all references to the minimum Python version have been updated correctly.
✅ Verification successful
Further verification needed: Unable to fully confirm Python version updates due to script errors. Please run additional verification scripts to ensure all references to the minimum Python version have been correctly updated.
Verification Successful: Minimum Python version updated to 3.9+
The
pyproject.tomlfile correctly specifiesrequires-python = ">=3.9", aligning with the PR objective of dropping Python 3.8 support. Additionally, the CI configuration files reference Python versions "3.10" and "3.11", ensuring compatibility and support for the updated Python versions.Please ensure that all documentation files, such as README files, are present and updated to reflect the new minimum Python version requirement.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for minimum Python version references in key project files # Test: Search for Python version references in README, setup.py, and CI config files echo "Checking README.md for Python version references:" rg --type md 'python' README.md echo "\nChecking setup.py for Python version references:" rg --type python 'python_requires' setup.py echo "\nChecking CI configuration files for Python version references:" rg --type yaml 'python-version' .github/workflows/*.yml .azure-pipelines/*.ymlLength of output: 2295
Script:
#!/bin/bash # Description: Enhanced check for minimum Python version references in key project files # Search for README files with different case sensitivities echo "Checking for any README files for Python version references:" rg 'python' README.* echo "\nChecking setup.py for Python version references without type constraint:" rg 'python_requires' setup.py # Search all YAML configuration files recursively for python-version echo "\nChecking all YAML configuration files for Python version references:" rg 'python-version' '**/*.yml' '**/*.yaml' # Additionally, search pyproject.toml if present echo "\nChecking pyproject.toml for Python version references:" rg 'python' pyproject.tomlLength of output: 1077
package/PartSegCore/image_transforming/swap_time_stack.py (1)
17-17: Approved: Improved type hinting for better readabilityThe change from
typing.Tupletotuplein the return type hint is a positive update. This modification:
- Aligns with modern Python type hinting practices (Python 3.9+).
- Improves code readability.
- Is consistent with the PR objective of dropping Python 3.8 support.
The functionality of the method remains unchanged, making this a safe and beneficial update.
package/PartSeg/common_gui/numpy_qimage.py (1)
8-8: Approved: Type annotation update aligns with modern Python practicesThe change from
typing.Tupletotuplein theColorMapDicttype annotation is correct and aligns with modern Python typing practices. This update:
- Uses the built-in
tupletype for type hinting, which became available in Python 3.9+.- Maintains the same semantic meaning as the previous annotation.
- Supports the PR objective of dropping Python 3.8 support, as this syntax is not available in Python 3.8.
This change improves code readability and future-proofs the type annotations without affecting the runtime behavior of the code.
.pre-commit-config.yaml (2)
3-3: Approved: Black version updateUpdating the Black pre-commit hook from version 24.8.0 to 24.10.0 is a good practice. This keeps the formatting tool up-to-date, potentially bringing in bug fixes and improvements.
1-2: Verify removal of Python 3.8 specificationThe AI summary mentions that the
default_language_versionsection specifying Python 3.8 has been removed. This aligns with the PR objective of dropping Python 3.8 support. However, this change is not visible in the provided code snippet.To confirm this change, please run the following command:
If the command produces no output, it confirms that the Python 3.8 specification has been successfully removed.
✅ Verification successful
Python 3.8 specification successfully removed
The
python: python3.8specification has been successfully removed from.pre-commit-config.yaml.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the removal of Python 3.8 specification # Expected: No output, indicating the absence of Python 3.8 specification grep -n "python: python3.8" .pre-commit-config.yamlLength of output: 2153
Script:
#!/bin/bash # Description: Verify the removal of Python 3.8 specification in .pre-commit-config.yaml # Expected: No output if "python: python3.8" has been successfully removed grep -n "python: python3.8" .pre-commit-config.yamlLength of output: 53
package/PartSegCore/analysis/analysis_utils.py (1)
29-29: LGTM! Type hint updated correctly.The change from
typing.Listtolistfor type hinting is correct and aligns with modern Python practices. This update is consistent with dropping support for Python 3.8 and using features available in Python 3.9+.To ensure consistency across the codebase, let's check if similar changes have been made in other files:
This script will help us verify if the type hint updates have been consistently applied across the project.
package/PartSeg/common_gui/image_adjustment.py (3)
1-1: LGTM: Import changes align with Python 3.9+ type hinting.The removal of
Dictimport fromtypingis appropriate as Python 3.9+ allows using built-indictfor type hinting. This change aligns with the PR objective of dropping Python 3.8 support.
Line range hint
1-16: Summary: Changes successfully update type hints for Python 3.9+ compatibility.The modifications in this file are minimal and focused, successfully updating the type hints to be compatible with Python 3.9+. These changes align with the PR objective of dropping Python 3.8 support. The core functionality and logic of the
ImageAdjustmentDialogclass remain unchanged, ensuring that the update is non-disruptive to the existing codebase.
16-16: LGTM: Constructor signature updated correctly.The change from
Optional[Dict[str, TransformBase]]toOptional[dict[str, TransformBase]]is correct and consistent with the import changes. This update maintains the same semantic meaning while leveraging Python 3.9+ type hinting capabilities.To ensure consistency across the codebase, let's verify the usage of
ImageAdjustmentDialog:✅ Verification successful
The constructor signature update from
Optional[Dict[str, TransformBase]]toOptional[dict[str, TransformBase]]has been correctly applied and no remaining usages of the old type hint were found. The changes are consistent across the codebase.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for any remaining usage of Dict[str, TransformBase] in relation to ImageAdjustmentDialog # Search for ImageAdjustmentDialog instantiations or references rg --type python -A 5 "ImageAdjustmentDialog" # Search for any remaining Dict[str, TransformBase] type hints rg --type python "Dict\[str,\s*TransformBase\]"Length of output: 157
Script:
#!/bin/bash # Description: Check for any remaining usage of Dict[str, TransformBase] in relation to ImageAdjustmentDialog # Search for ImageAdjustmentDialog instantiations or references in Python files rg -g '*.py' -A 5 "ImageAdjustmentDialog" # Search for any remaining Dict[str, TransformBase] type hints in Python files rg -g '*.py' "Dict\[str,\s*TransformBase\]"Length of output: 2952
package/PartSegCore/napari_plugins/save_tiff_layer.py (1)
2-2: LGTM: Import statement update aligns with Python 3.9+ practices.The removal of the
Listimport fromtypingis consistent with the PR objective of dropping Python 3.8 support. This change leverages the ability to use built-in types for type hinting in Python 3.9+, which is a recommended practice for modern Python development.package/PartSeg/common_gui/equal_column_layout.py (1)
15-15: LGTM: Type hint updated to use built-inlistThe change from
List[QLayoutItem]tolist[QLayoutItem]is correct and aligns with modern Python type hinting practices. This update is consistent with the PR objective of dropping Python 3.8 support, as this syntax is supported in Python 3.9+.Let's verify if there are any other occurrences of
Listfrom thetypingmodule in this file:✅ Verification successful
✅ No remaining
typing.Listusages foundAll instances of
Listfrom thetypingmodule have been successfully replaced with the built-inlisttype hints inequal_column_layout.py. This change aligns with modern Python practices and supports the PR's goal of dropping Python 3.8 compatibility.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for any remaining usage of typing.List in the file # Test: Search for 'from typing import' or 'import typing'. Expect: No matches rg --type python 'from typing import|import typing' package/PartSeg/common_gui/equal_column_layout.py # Test: Search for usage of List[. Expect: No matches rg --type python 'List\[' package/PartSeg/common_gui/equal_column_layout.pyLength of output: 243
Script:
#!/bin/bash # Description: Check for any remaining usage of typing.List in the file # Test: Search for 'from typing import' or 'import typing'. Expect: No matches rg 'from typing import|import typing' package/PartSeg/common_gui/equal_column_layout.py # Test: Search for usage of List[. Expect: No matches rg 'List\[' package/PartSeg/common_gui/equal_column_layout.pyLength of output: 153
package/PartSegCore/image_transforming/combine_channels.py (4)
2-2: LGTM: Import statement updated correctlyThe removal of
Listfrom the import statement is consistent with the changes made in the method signatures, aligning with the PR objective of updating type hints to use built-in types.
40-40: LGTM: Return type hint updated correctlyThe change from
Tupletotuplein the return type hint is consistent with the PR objective of updating type hints to use built-in types. This change maintains the same functionality while modernizing the type hinting.
Line range hint
1-62: Summary: Type hint updates improve code qualityThe changes in this file successfully update the type hints from
typing.Listandtyping.Tupleto the built-inlistandtupletypes. These modifications:
- Improve code readability
- Align with modern Python type hinting practices
- Support the PR objective of dropping Python 3.8 support
No functional changes were made to the code logic, ensuring that the existing behavior remains intact while modernizing the type annotations.
23-23: LGTM: Return type hint updated correctlyThe change from
Listtolistin the return type hint is consistent with the PR objective of updating type hints to use built-in types. This change maintains the same functionality while modernizing the type hinting.To ensure this change is compatible with the project's minimum Python version, let's verify the Python version specified in the project configuration:
✅ Verification successful
LGTM: Python version compatibility confirmed
The project's minimum Python version is 3.10, which is compatible with the updated type hint using
list.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check the minimum Python version specified in pyproject.toml or setup.py # Test 1: Check pyproject.toml if [ -f pyproject.toml ]; then echo "Checking pyproject.toml:" grep -i "python_version" pyproject.toml fi # Test 2: Check setup.py if [ -f setup.py ]; then echo "Checking setup.py:" grep -i "python_requires" setup.py fiLength of output: 329
package/PartSegCore/image_transforming/interpolate_image.py (2)
17-17: Approved: Type hint update improves readabilityThe change from
List[Union[str, AlgorithmProperty]]tolist[Union[str, AlgorithmProperty]]is a good modernization of the type hints. This update:
- Aligns with Python 3.9+ practices of using built-in types for type hinting.
- Improves code readability.
- Is backwards compatible with Python 3.9+.
This change is consistent with the PR objective of dropping Python 3.8 support and adopting more modern Python features.
Line range hint
1-35: Summary: Successful modernization of type hintsThe changes in this file successfully update the type hints to use built-in types (
listandtuple) instead of theirtypingmodule counterparts. These updates:
- Align with the PR objective of dropping Python 3.8 support.
- Improve code readability and maintainability.
- Follow modern Python 3.9+ practices for type hinting.
- Maintain backwards compatibility with Python 3.9+.
- Do not introduce any functional changes or potential bugs.
Overall, these changes represent a positive step in modernizing the codebase and preparing it for future Python versions.
package/PartSegCore/image_transforming/image_projection.py (2)
2-2: LGTM: Import statement updateThe removal of the
Tupleimport from thetypingmodule is appropriate as it's no longer used in the file. This change aligns with modern Python practices of using built-in types for type hinting, which is consistent with the PR objective of updating type hints and dropping support for older Python versions.
Line range hint
1-42: Overall assessment: Changes align with PR objectivesThe changes made to this file are consistent with the PR objective of updating type hints and dropping support for older Python versions. The modifications improve the code by utilizing more modern Python features without altering the underlying functionality. These updates contribute to a more maintainable and future-proof codebase.
To ensure that these changes haven't introduced any unintended consequences, please run the existing test suite for this module.
package/PartSegCore/analysis/calculate_pipeline.py (4)
26-26: Approved: Updated type hint to use built-indictThis change from
typing.Dicttodictis a good modernization of the type hinting syntax. It's consistent with dropping Python 3.8 support and uses the more concise built-in type, which is available in Python 3.9+. This improves readability and reduces dependencies on thetypingmodule.
28-28: Approved: Updated type hint to use built-inlistThis change from
typing.Listtolistis consistent with the previous update and continues the modernization of type hints. It further improves code readability and reduces reliance on thetypingmodule, which is beneficial for maintaining clean and up-to-date code.
57-57: Approved: Updated return type hint to use built-intupleThis change from
typing.Tupletotuplecompletes the pattern of updating to built-in types for type hinting in this file. These updates collectively modernize the code, improving readability and reducing dependencies on thetypingmodule. This is fully aligned with the PR objective of dropping Python 3.8 support and adopting more recent Python features.
Line range hint
26-57: Verify consistency of type hint updates across the codebaseThe changes in this file effectively update type hints to use built-in types, which is great for code modernization and readability. To ensure consistency, it would be beneficial to verify that similar updates have been applied throughout the entire codebase.
Here's a script to check for any remaining uses of
typing.Dict,typing.List, andtyping.Tuple:If this script returns any results, consider updating those instances as well for consistency.
package/PartSegCore/analysis/io_utils.py (1)
28-28: Approved: Updated type hint to use built-indictThis change from
typing.Dicttodictaligns with modern Python type hinting practices for Python 3.9+. It improves code readability and reduces dependencies on thetypingmodule, which is beneficial for maintaining the codebase.package/PartSegImage/channel_class.py (2)
2-2: Approved: Modernized type hintingThe changes in import statements and type hints align with modern Python practices:
- Removal of
Dictimport fromtyping.- Use of
dictinstead ofDictin type hints.These modifications improve code readability and are consistent with Python 3.9+ type hinting conventions. This change supports the PR objective of dropping Python 3.8 support and modernizing the codebase.
Also applies to: 83-83
Line range hint
1-85: Overall: Changes approved with minor suggestionsThe modifications in this file successfully achieve the following:
- Modernize type hinting practices.
- Ensure compatibility with both Pydantic 1 and 2.
- Maintain core functionality while improving code quality.
These changes align well with the PR objectives of dropping Python 3.8 support and updating the codebase. The implementation is thoughtful, maintaining backwards compatibility where necessary.
A few minor suggestions have been made for further improvement:
- Adding a comment to explain the purpose of new parameters in the Pydantic 2 version of
check_type_.- Reviewing and potentially addressing the TODO comment in the
__modify_schema__method.Overall, these changes are approved and contribute positively to the project's modernization efforts.
package/PartSegCore/sphinx/auto_parameters.py (2)
6-6: LGTM: Import statement updated correctlyThe removal of the
Dictimport from thetypingmodule is in line with the PR objective of updating type hints to use built-in types. TheAnyimport is correctly retained as it's still used in the file.
Line range hint
1-80: Overall impact: Positive changes aligned with PR objectivesThe changes in this file successfully update the type hinting to use built-in types, aligning with the PR objective of dropping Python 3.8 support. The modifications are focused on import statements and type annotations, leaving the core functionality intact. These updates improve code consistency with modern Python practices without introducing any potential issues or regressions.
package/PartSeg/common_backend/partially_const_dict.py (2)
2-3: LGTM: Import and type hint updates align with modern Python practices.The changes to import statements and type definitions are appropriate:
- Using
collections.abcinstead oftypingforIteratorandMutableMapping.- Removing the import of
Dictfromtyping.- Updating
RemovableInfoto use the built-intupletype.These modifications align with the PR objective of dropping Python 3.8 support and follow modern Python practices.
Also applies to: 10-10
22-22: LGTM: Class variable type hint updated correctly.The update of the
const_item_dicttype hint fromDict[str, Any]todict[str, Any]is correct and consistent with the other changes in the file. This modification aligns with modern Python type hinting practices and supports the transition away from Python 3.8.package/PartSeg/plugins/napari_widgets/utils.py (1)
53-53: Approved: Type hint modernizationThe change from
typing.Type[FormWidget]totype[FormWidget]as the return type annotation for thewidget_classmethod is a positive update. This modification:
- Simplifies the type hint by using the built-in
typeinstead oftyping.Type.- Aligns with modern Python type hinting practices.
- Supports the PR's objective of dropping Python 3.8 support and modernizing the codebase.
The change doesn't affect the functionality of the method, only improving its type annotation.
package/PartSeg/plugins/napari_widgets/colormap_control.py (3)
1-2: LGTM: Import statements are consistent with type hint changes.The import statements have been correctly updated to remove
DictandTuplefromtyping, which is consistent with the use of built-indictandtuplefor type hinting on line 48. The import ofIterablefromcollections.abcis also a good practice for Python 3.9+.
48-48: Approved: Updated type hint to use built-in types.The change from
Dict[str, Tuple[Colormap, bool]]todict[str, tuple[Colormap, bool]]is a good modernization of the type hint. This approach is recommended for Python 3.9+ as it uses built-in types, which can lead to better performance and readability. The semantic meaning of the type hint remains the same, ensuring backward compatibility.
Line range hint
1-48: LGTM: Type hinting is consistent throughout the file.After reviewing the entire file, I can confirm that the type hinting is consistent. The change made to line 48 is the only place where
DictandTuplewere used, and it has been updated appropriately. Other type hints, such asOptional, continue to use thetypingmodule, which is correct for maintaining compatibility with Python versions prior to 3.10.package/PartSeg/plugins/napari_widgets/lables_control.py (3)
18-18: Approved: Updated type annotation to use built-inlistThe change from
List[Sequence[float]]tolist[Sequence[float]]is a positive update. It aligns with modern Python type hinting practices, which became available in Python 3.9+. This modification:
- Simplifies the import statements by removing the need for
from typing import List.- Maintains the same semantic meaning as the previous annotation.
- Doesn't affect the runtime behavior of the code.
This change is consistent with the PR objective of dropping Python 3.8 support and modernizing the codebase.
58-58: Approved: Consistent update of type annotationThe change from
List[Sequence[float]]tolist[Sequence[float]]in the_label_showmethod signature is consistent with the previous update in theNapariLabelShowclass. This modification:
- Maintains consistency throughout the codebase.
- Aligns with modern Python type hinting practices (Python 3.9+).
- Preserves the semantic meaning of the type annotation.
This change further supports the PR objective of dropping Python 3.8 support and ensures a uniform approach to type hinting across the file.
Line range hint
1-91: Summary: Consistent type annotation updatesThe changes in this file are focused on updating type annotations from
typing.Listto the built-inlisttype. These modifications:
- Align with modern Python type hinting practices (Python 3.9+).
- Support the PR objective of dropping Python 3.8 support.
- Maintain code semantics while simplifying import statements.
The updates are straightforward and don't introduce any risks or changes in functionality. However, to ensure a comprehensive update:
Run the following script to check for any remaining usage of
typing.Listin Python files:This verification will help ensure that the transition from
typing.Listto built-inlisthas been applied consistently across the entire codebase.✅ Verification successful
Verified: Type annotations updated correctly
The type annotations in
package/PartSeg/plugins/napari_widgets/lables_control.pyhave been successfully updated fromtyping.Listto the built-inlisttype. These changes:
- Align with modern Python type hinting practices (Python 3.9+).
- Support the PR objective of dropping Python 3.8 support.
- Maintain code semantics while simplifying import statements.
No issues were found related to this specific file.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for remaining usage of typing.List in Python files # Test: Search for 'from typing import List' or 'from typing import ... List ...' echo "Checking for 'from typing import List':" rg --type python 'from\s+typing\s+import\s+(.*\s*,\s*)*List(\s*,\s*.*)*' # Test: Search for type annotations using List[...] echo "Checking for type annotations using List[...]:" rg --type python '\bList\[' # Note: This script might produce false positives if 'List' is used in comments or strings. # Manual verification of the results is recommended.Length of output: 364
Script:
#!/bin/bash # Description: Check for remaining usage of typing.List in Python files # Test: Search for 'from typing import List' or 'from typing import ... List ...' echo "Checking for 'from typing import List':" rg --type py 'from\s+typing\s+import\s+(.*\s*,\s*)*List(\s*,\s*.*)*' # Test: Search for type annotations using List[...] echo "Checking for type annotations using List[...]:" rg --type py '\bList\[' # Note: This script might produce false positives if 'List' is used in comments or strings. # Manual verification of the results is recommended.Length of output: 2644
package/PartSeg/plugins/old_partseg/old_partseg.py (2)
67-67: Approved: Type hint modernizationThe change from
typing.Listtolistfor theload_locationsparameter is a positive update. This modification:
- Aligns with the PR objective of dropping Python 3.8 support.
- Utilizes the more concise built-in
listtype hint introduced in Python 3.9.- Improves code readability without altering functionality.
- Is part of a broader effort to modernize type hints across the codebase.
This change is low-risk and contributes to maintaining up-to-date coding practices.
Line range hint
28-62: Verify compatibility of_loadmethod with updated Python versionThe
_loadmethod is crucial for handling the old project format. While the current changes don't directly affect this method, it's important to ensure its compatibility with the updated Python version (3.9+) and any potential changes in dependencies.To verify the compatibility and usage of the
_loadmethod, you can run the following script:This script will help identify any potential compatibility issues or areas that might need attention due to the Python version update.
✅ Verification successful
Compatibility Verified: The
_loadmethod inold_partseg.pyis compatible with Python 3.9+.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for usage of _load method and verify its compatibility # Search for usage of _load method echo "Searching for usage of _load method:" rg --type python "_load\(" package/PartSeg/plugins/old_partseg/old_partseg.py # Check for any TODO or FIXME comments related to Python version compatibility echo "Checking for TODO or FIXME comments related to Python version compatibility:" rg --type python -i "TODO|FIXME" -C 2 package/PartSeg/plugins/old_partseg/old_partseg.py # Look for any version-specific imports or code echo "Checking for version-specific imports or code:" rg --type python "import.*sys|sys\.version_info" package/PartSeg/plugins/old_partseg/old_partseg.pyLength of output: 714
Script:
#!/bin/bash # Description: Check for usage of _load method and verify its compatibility # Search for usage of _load method in .py files echo "Searching for usage of _load method:" rg "_load\(" --glob "*.py" package/PartSeg/plugins/old_partseg/old_partseg.py # Check for any TODO or FIXME comments related to Python version compatibility in .py files echo "Checking for TODO or FIXME comments related to Python version compatibility:" rg -i "TODO|FIXME" -C 2 --glob "*.py" package/PartSeg/plugins/old_partseg/old_partseg.py # Look for any version-specific imports or code in .py files echo "Checking for version-specific imports or code:" rg "import.*sys|sys\.version_info" --glob "*.py" package/PartSeg/plugins/old_partseg/old_partseg.pyLength of output: 838
package/PartSeg/_roi_mask/segmentation_info_dialog.py (2)
1-1: LGTM: Import statement updated correctlyThe removal of
Dictfrom thetypingimport is consistent with the PR objective of updating type hints. This change correctly transitions to using the built-indicttype instead oftyping.Dict, which is appropriate for Python 3.9+. The continued import ofOptionalandCallableis correct as these are still used in the code and don't have direct built-in equivalents.
Line range hint
1-48: Overall changes look good and align with PR objectivesThe changes in this file are consistent with the PR objective of dropping Python 3.8 support and updating type hints. Here's a summary of the impacts:
- Improved code readability with modern type hinting practices.
- No changes to runtime behavior or functionality.
- Backwards compatible with Python 3.9+.
- Successfully transitions from
typing.Dictto built-indictfor type hinting.These updates contribute to a more maintainable and future-proof codebase.
package/PartSeg/_launcher/check_version.py (1)
Line range hint
1-93: Suggest improvement in error handling and verify imports.The overall structure and functionality of the file look good. Here are some suggestions for improvement:
- Consider adding more specific exception handling in the
runmethod. Currently, it catches all exceptions with a broadexcept Exceptionclause. It might be beneficial to catch and handle specific exceptions separately.Here's a suggested improvement for the exception handling:
try: # ... existing code ... except (KeyError, urllib.error.URLError): # Handle network-related errors pass except json.JSONDecodeError: # Handle JSON parsing errors pass except Exception as e: # Handle other unexpected errors with sentry_sdk.new_scope() as scope: scope.set_tag("auto_report", "true") scope.set_tag("check_version", "true") sentry_sdk.capture_exception(e)
- To ensure all necessary imports are present and there are no unused imports, let's run a verification script.
This script will help identify any unused imports or missing imports in the file.
package/PartSegCore/roi_info.py (3)
23-23: LGTM: Type hint update aligns with modern Python practices.The change from
List[slice]tolist[slice]is appropriate and aligns with the PR objective of dropping Python 3.8 support. This update leverages the ability to use built-in types for type hints in Python 3.9+, improving code readability.
48-49: LGTM: Consistent type hint updates in__init__method.The changes from
Dicttodictin the type hints forannotationsandalternativeparameters are consistent with the updates elsewhere in the file. These changes align with the PR objective of dropping Python 3.8 support and adhere to modern Python type hinting practices.
Line range hint
1-109: Overall assessment: Type hint updates successfully modernize the code.The changes in this file consistently update type hints from
typing.Listandtyping.Dictto their built-in counterpartslistanddict. These updates align with the PR objective of dropping Python 3.8 support and adopting modern Python type hinting practices. The changes improve code readability without altering the functionality of the classes and methods.Key points:
- All changes are consistent throughout the file.
- No functional changes were made; only type hint updates were performed.
- The updates reduce the need for importing from the
typingmodule.These changes contribute positively to the codebase by modernizing the type hinting approach and preparing the project for newer Python versions.
package/PartSeg/common_gui/stack_image_view.py (1)
22-22: LGTM! Consider updating minimum Python version.The change from
Union[List[ImageView], ImageView]toUnion[list[ImageView], ImageView]is correct and aligns with modern Python type hinting practices. This modification supports the PR objective of dropping Python 3.8 support, as built-in generics were introduced in Python 3.9.To ensure consistency across the project, please verify that the minimum required Python version has been updated in the project's metadata (e.g., setup.py, pyproject.toml). Run the following script to check:
✅ Verification successful
Minimum Python version requirement is correctly specified.
The project's
pyproject.tomlfile specifiesrequires-python = ">=3.9", ensuring alignment with the recent type hinting changes and the goal to drop Python 3.8 support.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check minimum Python version in project metadata # Test: Search for Python version specification in setup.py or pyproject.toml echo "Checking setup.py:" rg 'python_requires' setup.py || echo "No Python version found in setup.py" echo -e "\nChecking pyproject.toml:" rg 'requires-python' pyproject.toml || echo "No Python version found in pyproject.toml"Length of output: 284
package/PartSegCore/image_operations.py (1)
1-1: Approved: Import statement update forIterableThe change from
typing.Iterabletocollections.abc.Iterableis a good practice. It aligns with Python's type hinting recommendations and is consistent with dropping support for Python 3.8.package/PartSegCore/project_info.py (5)
3-3: LGTM: Import statement updated correctlyThe removal of
ListandDictfrom the import statement is appropriate and consistent with the transition to using built-in types for type hinting.
35-36: LGTM: Type hints updated to use built-in typesThe changes to use
dictinstead ofDictfor type hinting are appropriate and align with modern Python practices. This improves compatibility with newer Python versions while maintaining the same semantic meaning.
68-68: LGTM: Return type hint updated to use built-in tupleThe change from
Tupletotuplein the return type hint is appropriate and consistent with the transition to using built-in types. This maintains the same semantic meaning while improving compatibility with newer Python versions.
95-97: LGTM: Class variable type hints updated to use built-in typesThe changes to use
dictinstead ofDictandlistinstead ofListfor type hinting of class variables are appropriate. These updates align with modern Python practices and improve compatibility with newer Python versions while maintaining the same semantic meaning.
Line range hint
1-143: Summary: Type hint updates improve compatibility and follow modern practicesThe changes in this file consistently update type hints to use built-in types (
dictandlist) instead of theirtypingmodule counterparts (DictandList). These modifications align with the PR objective of dropping support for Python 3.8 and follow modern Python type hinting practices.Key points:
- All changes are non-functional and focus solely on type hint updates.
- The semantic meaning of all type hints remains unchanged.
- These updates improve compatibility with newer Python versions.
- One minor docstring update is suggested for full consistency.
Overall, these changes contribute to modernizing the codebase and preparing it for future Python versions.
package/PartSeg/_roi_mask/batch_proceed.py (3)
22-22: LGTM! Consistent use of built-in types for type hinting.The change from
Tupletotuplein the type hint forsave_prefixis consistent with the move to use built-in types for type hinting in Python 3.9+. This change maintains the same meaning while updating the syntax.
Line range hint
1-114: Summary: Changes align well with PR objectivesThe modifications in this file successfully update the type hints to use built-in types (
list,tuple) instead of theirtypingmodule counterparts. These changes are consistent with the PR objective of dropping Python 3.8 support and adopting more modern Python type hinting practices (Python 3.9+).Key points:
- Import statements have been updated to remove unnecessary imports from
typing.- Type hints in
BatchTaskandBatchProceedclasses have been updated to use built-in types.- No functional changes have been made to the code logic.
These updates improve code readability and maintainability while ensuring compatibility with newer Python versions. The changes are well-executed and align perfectly with the PR's goals.
6-6: LGTM! Verify usage of built-in types throughout the file.The change to import only necessary types from
typingis consistent with modern Python type hinting practices (Python 3.9+). This aligns well with the PR objective of dropping Python 3.8 support.Let's verify that the built-in types are used consistently throughout the file:
package/PartSegCore/napari_plugins/loader.py (4)
18-18: Approved: Updated type hint to use built-inlisttypeThis change from
typing.List[int]tolist[int]aligns with Python 3.9+ type hinting syntax. It improves code readability and reduces the need for importing from thetypingmodule. This modification is consistent with dropping support for Python 3.8.
21-21: Approved: Consistent type hint update in main function signatureThe change from
typing.List[int]tolist[int]in the mainadjust_colorfunction signature is consistent with the previous overload modification. This ensures type consistency throughout the function definitions and aligns with the PR objective of updating the codebase for newer Python versions.
Line range hint
1-151: Summary: File changes align with PR objectives and improve type hintingThe modifications in this file consistently update type hints to use built-in types instead of those from the
typingmodule. These changes align with the PR objective of dropping support for Python 3.8 and adopting modern Python type hinting practices. The updates improve code readability and prepare the codebase for newer Python versions.
138-138: Approved: Updated type hint to use built-intypeThe change from
typing.Type[LoadBase]totype[LoadBase]in thepartseg_loaderfunction signature is consistent with the move towards using built-in types for annotations in Python 3.9+. This aligns with the PR objective of updating the codebase for newer Python versions.To ensure compatibility with type checking tools, please run the following command:
package/PartSeg/_launcher/main_window.py (1)
37-37: Approved: Type hint modernizationThe change from
Type[BaseMainWindow]totype[BaseMainWindow]is a positive modernization of the type hinting syntax. This update is consistent with the PR objective of dropping Python 3.8 support and adopting more recent Python features.Key points:
typeis a built-in type in Python, whileTypeis from thetypingmodule.- This change is backwards compatible with Python 3.9+.
- The semantic meaning of the type hint remains the same.
This modification improves code readability and aligns with current Python best practices.
package/PartSegImage/image_writer.py (3)
127-127: LGTM: Type hint update aligns with PR objectiveThe change from
typing.Dict[str, typing.Any]todict[str, typing.Any]is appropriate and aligns with the PR objective of dropping Python 3.8 support. This update leverages the built-in types for type hinting, which is supported from Python 3.9 onwards.
153-153: LGTM: Consistent type hint updateThis change from
typing.Dict[str, typing.Union[str, float]]todict[str, typing.Union[str, float]]is consistent with the previous update and aligns with the PR objective of dropping Python 3.8 support. It leverages the built-indicttype for type hinting, which is supported from Python 3.9 onwards.
Line range hint
1-1: Verify method signature changes mentioned in the AI summaryThe AI-generated summary mentions updates to the method signatures of
saveandsave_maskin theIMAGEJImageWriterclass, specifically changing the default value of thecompressionparameter from"ADOBE_DEFLATE"to"". However, these changes are not visible in the current diff.Could you please verify if these changes were made in a previous commit, reverted, or if the summary is incorrect?
To check the current state of these method signatures, you can run:
package/PartSegCore/register.py (1)
115-115: Approved: Type hint update aligns with Python 3.9+ supportThe change from
Type[AlgorithmDescribeBase]totype[AlgorithmDescribeBase]in the function signature is correct and aligns with the PR objective of dropping Python 3.8 support. This update leverages PEP 585, which allows the use of built-in types as generic types in Python 3.9+. The modification enhances code readability and modernizes the type hinting approach.package/PartSeg/common_gui/custom_load_dialog.py (7)
14-16: LGTM: Type annotation updates for Python 3.9+ compatibilityThe changes to
LoadPropertyclass improve type hinting by usinglistandtypeinstead oftyping.Listandtyping.Type. This update is consistent with dropping Python 3.8 support and adopting modern Python type hinting practices.
19-19: LGTM: IORegister type alias updated for Python 3.9+ compatibilityThe
IORegistertype alias has been updated to usedictinstead oftyping.Dict, which is consistent with dropping Python 3.8 support and adopting modern Python type hinting practices.
86-86: LGTM: Type annotation update in CustomLoadDialog constructorThe type annotation for the
historyparameter in theCustomLoadDialogconstructor has been updated to uselistinstead oftyping.List. This change is consistent with dropping Python 3.8 support and adopting modern Python type hinting practices.
119-119: LGTM: Type annotation update in CustomLoadDialog.get_result methodThe type annotation for
chosen_classin theget_resultmethod has been updated to usetype[LoadBase]instead oftyping.Type[LoadBase]. This change is consistent with dropping Python 3.8 support and adopting modern Python type hinting practices.
126-126: LGTM: Type annotation update in PLoadDialog constructorThe type annotation for the
load_registerparameter in thePLoadDialogconstructor has been updated to usedictinstead oftyping.Dict. This change is consistent with dropping Python 3.8 support and adopting modern Python type hinting practices.
165-165: LGTM: Type annotation update in SelectDirectoryDialog constructorThe type annotation for the
settings_pathparameter in theSelectDirectoryDialogconstructor has been updated to uselistinstead oftyping.List. This change is consistent with dropping Python 3.8 support and adopting modern Python type hinting practices.
Line range hint
1-194: Summary: Consistent type annotation updates for Python 3.9+ compatibilityThe changes in this file consistently update type annotations to use built-in types (
list,dict,type) instead of theirtypingmodule counterparts. These updates align with the PR objective of dropping Python 3.8 support and adopting modern Python type hinting practices available in Python 3.9+.Key points:
- No functional changes were made; only type annotations were updated.
- The changes improve code readability and maintainability.
- The updates are consistent throughout the file, indicating a thorough review and modification process.
These changes contribute to a more modern and forward-compatible codebase, which is beneficial for long-term maintenance and development.
package/PartSeg/common_backend/base_argparser.py (3)
8-11: LGTM: Import changes align with modern Python practices.The addition of
Sequencefromcollections.abcand the retention ofOptionalfromtypingare appropriate for the updated method signatures and align well with modern Python typing practices. These changes are consistent with dropping support for Python 3.8.
Line range hint
95-100: LGTM: Improved type hints and argument validation.The changes to the
parse_argsmethod are excellent improvements:
- The updated method signature with
Optional[Sequence[str]]enhances type safety and clarity.- The new check preventing simultaneous setting of
--always_reportand--no_reportis a good practice that avoids conflicting configurations.These modifications contribute to more robust and type-safe argument parsing.
Line range hint
1-134: Summary: Excellent improvements aligned with dropping Python 3.8 support.Overall, the changes in this file are well-implemented and align perfectly with the PR objective of dropping Python 3.8 support. Key improvements include:
- Updated imports and type hints for better compatibility with modern Python versions.
- Enhanced argument definitions and parsing in the
CustomParserclass.- Improved version-specific handling for Sentry SDK initialization.
These changes contribute to better type safety, clearer code, and improved compatibility. The minor suggestions provided earlier are optional and do not impact the overall quality of the implementation.
azure-pipelines.yml (2)
44-44: LGTM: Python version update in formatting_check stageThe update from Python 3.8 to 3.9 in the formatting_check stage is a good step towards dropping Python 3.8 support. This conservative update should minimize the risk of incompatibilities.
To ensure that the formatting tools work correctly with Python 3.9, run the following command in your local environment:
python3.9 -m pip install pre-commit python3.9 -m pre_commit run --allIf these commands execute without errors and produce the expected results, it confirms that the formatting tools are compatible with Python 3.9.
26-26: LGTM: Python version update in GetTestData stageThe update from Python 3.9 to 3.11 in the GetTestData stage aligns with the PR objective to drop Python 3.8 support. This change should be safe, but it's worth verifying that all scripts and dependencies in this stage are compatible with Python 3.11.
To ensure compatibility, you can run the following command in your local environment:
If these commands execute without errors, it confirms that the scripts are compatible with Python 3.11.
.github/workflows/tests.yml (2)
93-93: LGTM: Consistent update of Python version matrix.The Python version matrix in the
base-test-mainjob has been updated consistently with thebase-testjob. This ensures that the same Python versions (3.9 through 3.12) are tested for both pull requests and pushes to main branches.
53-53: LGTM: Python version matrix updated correctly.The Python version matrix has been updated to remove 3.8 and now includes versions 3.9 through 3.12. This change aligns with the PR objective of dropping support for Python 3.8 and keeps the project up-to-date with the latest Python releases.
To ensure consistency, let's verify that this change is reflected in other parts of the workflow:
✅ Verification successful
Verification Successful: No remaining references to Python 3.8 found.
All instances of Python 3.8 have been successfully removed from the workflow file.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for any remaining references to Python 3.8 in the workflow file # Test: Search for Python 3.8 references rg '3\.8' .github/workflows/tests.yml # Test: Verify Python version ranges in other jobs rg 'python_version:.*3\.\d+' .github/workflows/tests.ymlLength of output: 681
package/PartSeg/common_gui/custom_save_dialog.py (4)
18-18: LGTM: Updated type hint syntaxThe change from
typing.List[str]tolist[str]aligns with modern Python type hinting practices (Python 3.9+). This update simplifies the type annotation and improves readability while maintaining the same functionality.
26-26: LGTM: Simplified type hint for class typesThe change from
typing.Type[FormWidget]totype[FormWidget]is a good modernization of the type hint syntax. This update is consistent with Python 3.9+ practices and improves code readability while maintaining the same semantic meaning.
61-61: LGTM: Consistent type hint updateThe change from
typing.List[str]tolist[str]for thehistoryparameter is consistent with the previous updates in this file. This modernization improves code readability and aligns with Python 3.9+ type hinting practices.
Line range hint
18-61: Summary: Type hint modernization aligned with dropping Python 3.8 supportThe changes in this file consistently update type hints from
typing.Listandtyping.Typeto their built-in equivalentslistandtype. These updates align with the PR objective of dropping Python 3.8 support and adopting modern Python type hinting practices.Key points:
- Improved readability and simplified syntax.
- Maintains backwards compatibility with Python 3.9+.
- No functional changes to the code logic.
Recommendation:
Ensure that the project's minimum supported Python version is updated in the documentation and any relevant configuration files (e.g., setup.py, pyproject.toml) to reflect the drop of Python 3.8 support.To verify the project's minimum Python version has been updated, run:
✅ Verification successful
Python Version Update Verified
The project's configuration files, including
tox.iniand GitHub Actions workflows, indicate that Python versions 3.9 and above are now supported. Python 3.8 is no longer included in the testing matrix, aligning with the PR's objective to drop Python 3.8 support.Action Items:
- Update the project's documentation and configuration files (e.g.,
setup.py,pyproject.tomlif present) to explicitly state the minimum supported Python version.- Ensure that all references to Python versions within the codebase reflect this change for consistency.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Check for Python version specifications in key files echo "Checking setup.py:" rg 'python_requires' setup.py echo "\nChecking pyproject.toml:" rg '(python|Python).*=.*"[0-9]' pyproject.toml echo "\nChecking README.md:" rg -i 'python.*3\.[0-9]+' README.mdLength of output: 329
Script:
#!/bin/bash # Searching for Python version specifications in additional configuration and workflow files echo "Checking setup.cfg:" rg 'python_requires|python_version' setup.cfg echo "\nChecking tox.ini:" rg 'basepython|envlist|python_version' tox.ini echo "\nChecking Pipfile:" rg 'python_version' Pipfile echo "\nChecking GitHub Actions workflows:" rg 'python-version' .github/workflows/** echo "\nChecking for shebangs specifying Python version in scripts:" rg -R '^#!.*/python3\.[0-9]+' scripts/Length of output: 2983
package/PartSeg/_roi_analysis/partseg_settings.py (2)
34-34: LGTM: Updated type hint forsave_locations_keysThe change from
typing.ClassVar[typing.List[str]]totyping.ClassVar[list[str]]is correct and aligns with modern Python type hinting practices. This update is consistent with dropping support for Python 3.8 and using features available in Python 3.9+.
135-135: LGTM: Updated return type hint forget_save_listThe change from
typing.List[SaveSettingsDescription]tolist[SaveSettingsDescription]is correct and consistent with the updates made elsewhere in the file. This modernization of type hints aligns with Python 3.9+ practices and the PR's objective.package/PartSeg/common_gui/select_multiple_files.py (1)
91-91: LGTM! Consider similar updates in other files.The change from
List[MaskMapper]tolist[MaskMapper]is correct and aligns with modern Python type hinting practices (Python 3.9+). This update is consistent with the PR's objective of dropping support for Python 3.8.To ensure consistency across the project, please run the following script to check for any remaining usage of
typing.List:If the script returns any results, consider updating those occurrences as well.
✅ Verification successful
Update Shell Script to Enable Multiline Mode
The previous script encountered a regex error. Please use the updated script below with multiline mode enabled:
Update Shell Script to Target Python Files Directly
The previous script failed to recognize the
pythonfile type. Please use the updated script below, which targets.pyfiles using a glob pattern:
Verification Successful: No Remaining
typing.ListUsages FoundThe search for remaining
typing.Listusages yielded no results. All type annotations have been updated to use the built-inlisttype.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for remaining usage of typing.List in Python files # Test: Search for 'from typing import List' or 'import typing' followed by 'typing.List' rg --type python -e 'from\s+typing\s+import.*List' -e 'import\s+typing.*\n.*typing\.List'Length of output: 283
Script:
# Description: Check for remaining usage of typing.List in Python files # Test: Search for 'from typing import List' or 'import typing' followed by 'typing.List' rg -U --type python -e 'from\s+typing\s+import.*List' -e 'import\s+typing.*\n.*typing\.List'Length of output: 125
Script:
# Description: Check for remaining usage of typing.List in Python files # Test: Search for 'from typing import List' or 'import typing' followed by 'typing.List' rg -U --glob '*.py' -e 'from\s+typing\s+import.*List' -e 'import\s+typing.*\n.*typing\.List'Length of output: 94
package/PartSeg/common_gui/napari_viewer_wrap.py (2)
2-2: LGTM: Updated import and type hint.The changes in the import statement and type hint are consistent with the PR objective of dropping Python 3.8 support:
- Adding
Optionalimport fromtypingmodule (line 2) is appropriate for its usage in the code.- Changing the return type hint of
get_colormapsmethod fromList[Optional[Colormap]]tolist[Optional[Colormap]](line 49) aligns with modern Python type hinting practices.These updates contribute to a more standardized and forward-compatible codebase.
Also applies to: 49-49
Line range hint
214-248: LGTM: Viewer class implementation.The Viewer class implementation remains consistent with the PR objectives. It correctly:
- Initializes the SynchronizeWidget with the provided settings and viewer name.
- Adds the widget to the left area of the window.
- Provides a flexible
create_initial_layersmethod for synchronizing various layer types.No changes were required in this class to support the removal of Python 3.8, which is appropriate.
package/PartSeg/common_gui/mask_widget.py (1)
112-112: Approved: Type hint update aligns with modern Python practicesThe change from
Listtolistin the return type hint is a good update. This modification:
- Aligns with modern Python type hinting practices.
- Simplifies the imports by removing the need for
Listfrom thetypingmodule.- Maintains compatibility with newer Python versions while dropping support for Python 3.8.
The functionality of the method remains unchanged, making this a safe and beneficial update.
package/PartSegCore/segmentation/algorithm_base.py (5)
2-2: LGTM: Updated import forMutableMappingThe change from
typing.MutableMappingtocollections.abc.MutableMappingis appropriate and aligns with modern Python practices. This update is consistent with dropping support for Python 3.8 and ensures compatibility with newer Python versions.
71-74: LGTM: Updated type annotations inROIExtractionResultThe changes from
Dicttodictin the type annotations foradditional_layers,roi_annotation, andalternative_representationare appropriate. These updates align with modern Python type hinting practices and improve code readability while maintaining the same functionality.
140-140: LGTM: Updated type annotation inROIExtractionAlgorithmThe change from
Dict[str, Any]todict[str, Any]for thenew_parametersattribute is appropriate. This update aligns with modern Python type hinting practices and improves code consistency with the other changes in this file.
Line range hint
1-280: Summary: Successful update of type annotationsThe changes made to this file successfully update the type annotations from
typing.Dicttodict, which is consistent with modern Python practices and the PR objective of dropping support for Python 3.8. These updates improve code readability and compatibility with newer Python versions without altering the file's functionality.The modifications are focused and well-executed, maintaining the overall structure and purpose of the classes and functions within the file. This update contributes to a more consistent and forward-compatible codebase.
Line range hint
1-280: Consider a comprehensive update of type annotationsWhile the changes made are appropriate and consistent, there might be an opportunity to update other type annotations throughout the file for complete consistency with modern Python practices. Additionally, given the complexity of the classes and functions in this file, it would be prudent to review and potentially update the associated unit tests to ensure they remain compatible with these changes.
To verify the consistency of type annotations and identify potential areas for further updates, you can run the following script:
This script will help identify any remaining instances of
typing.Listortyping.Dictthat could be updated, as well as locate the corresponding test file for review.package/PartSegCore/analysis/batch_processing/parallel_backend.py (6)
28-28: LGTM: Updated import statement aligns with Python 3.9+ usageThe removal of
ListandDictimports fromtypingis consistent with the PR objective of dropping Python 3.8 support. This change leverages the built-in generics available in Python 3.9+, which is a good modernization of the codebase.
71-71: LGTM: Updated return type hint to use built-in typesThe change from
List[Tuple[uuid.UUID, Any]]tolist[tuple[uuid.UUID, Any]]is a good update. It maintains the same semantic meaning while using the more modern built-in types for generics, which is consistent with Python 3.9+ practices.
87-87: LGTM: Updated parameter type hint to use built-in listThe change from
Listtolistfor theindividual_parameters_listparameter is appropriate. It maintains the same meaning while adopting the more modern built-in type for generics, which is in line with Python 3.9+ practices.
210-210: LGTM: Updated complex type hint to use built-in typesThe change from
Dict[uuid.UUID, Tuple[Any, Callable[[Any, Any], Any]]]todict[uuid.UUID, tuple[Any, Callable[[Any, Any], Any]]]is well-executed. It adopts the modern built-in types for generics while preserving the nested structure of the type hint. This update maintains the same semantic meaning and improves readability, aligning with Python 3.9+ practices.
218-218: LGTM: Updated parameter type hint to use built-in tupleThe change from
Tuple[Any, uuid.UUID]totuple[Any, uuid.UUID]for thevalparameter is appropriate. It maintains the same meaning while adopting the more modern built-in type for generics, which is in line with Python 3.9+ practices.
Line range hint
1-282: Summary: Successful migration to built-in type hints with minor improvement suggestionThe changes in this file successfully update the type hints from the
typingmodule to built-in types, which is consistent with the PR objective of dropping Python 3.8 support. These updates improve code readability and align with modern Python type hinting practices for Python 3.9+.All changes have been approved, with one minor suggestion for improvement:
- Consider updating the type hint for
calculation_dictin thespawn_workerfunction to match the more specific type used in theBatchWorkerconstructor.Overall, this file update effectively modernizes the type hinting approach while maintaining the original functionality.
package/PartSeg/common_gui/advanced_tabs.py (1)
203-203: LGTM: Updated type hint improves readability and Python version compatibility.The change from
List[str]tolist[str]is a good modernization of the type hint syntax. This update:
- Aligns with the PR objective of dropping Python 3.8 support.
- Improves code readability by using the built-in
listtype.- Maintains the same type information without changing the function's behavior.
package/PartSeg/common_gui/label_create.py (6)
7-7: LGTM: Import changes align with modern Python practicesThe changes to the import statements are appropriate:
- Importing
Sequencefromcollections.abcinstead oftyping.- Removing the import of
Listfromtypingas it's no longer needed with the use of built-inlist.These changes are consistent with Python 3.9+ type hinting practices and align well with the PR objective of dropping support for Python 3.8.
Also applies to: 11-11
79-79: LGTM: Type hint update in LabelShow classThe change from
List[Sequence[float]]tolist[Sequence[float]]for thelabelparameter is appropriate. It maintains the intended functionality while updating the type hint to use the built-inlisttype, which is consistent with modern Python practices and the PR objective.
184-184: LGTM: Consistent type hint update in LabelChoose classThe change from
List[Sequence[float]]tolist[Sequence[float]]for thelabelparameter in the_label_showmethod is consistent with the previous updates. This change maintains the method's functionality while aligning with modern Python type hinting practices.
292-292: LGTM: Return type hint update in LabelEditor classThe change from
List[List[int]]tolist[list[int]]for the return type of theget_colorsmethod is appropriate. This update maintains consistency with the other changes in the file and aligns with modern Python type hinting practices without altering the method's functionality.
333-333: LGTM: Type hint updates in LabelsLoad classThe changes in the
LabelsLoadclass are appropriate:
- The
load_locationsparameter type hint is updated fromList[Union[str, BytesIO, Path]]tolist[Union[str, BytesIO, Path]].- The return type hint is changed from
List[List[float]]tolist[list[float]].These updates maintain consistency with the other changes in the file and align with modern Python type hinting practices without altering the method's functionality.
Also applies to: 337-337
Line range hint
1-371: LGTM: Consistent type hint updates throughout the fileThe changes in this file are consistent and focused on updating type hints from
typing.Listto the built-inlisttype. These updates align well with the PR objective of dropping support for Python 3.8 and adopting modern Python type hinting practices. The changes maintain the existing functionality while improving code readability and consistency with newer Python versions.Key points:
- Import statements have been updated appropriately.
- All occurrences of
Listhave been replaced withlistin type hints.- Nested list type hints have been correctly updated.
- The changes are consistent across different classes and methods.
These updates contribute to a more modern and maintainable codebase without introducing any functional changes or potential issues.
package/PartSeg/_roi_analysis/profile_export.py (1)
156-159: LGTM! Type hint updates align with modern Python practices.The changes to the type hints in the
ImportDialogconstructor are appropriate and beneficial:
- Using
dictinstead oftyping.Dictforimport_dictandlocal_dict.- Using
typeinstead oftyping.Typeforviewerandexpected_type.These updates align with PEP 585 and are valid for Python 3.9+. They improve code readability and take advantage of newer Python features, which is consistent with dropping support for Python 3.8.
package/PartSeg/common_gui/universal_gui_part.py (3)
123-123: LGTM: Updated type annotation improves readabilityThe change from
typing.Tuple[float, float]totuple[float, float]for thedata_rangeparameter type annotation is a good improvement. This update:
- Aligns with the PR objective of dropping Python 3.8 support.
- Utilizes the more concise built-in types for type hinting, which is recommended in Python 3.9+.
- Improves code readability without changing the underlying functionality.
284-284: LGTM: Consistent update to type annotationThe change from
typing.List[str]tolist[str]for thetext_listparameter type annotation is consistent with the previous update. This change:
- Maintains consistency in using built-in types for type hinting throughout the codebase.
- Aligns with the PR objective of dropping Python 3.8 support.
- Improves code readability without altering the functionality.
Line range hint
1-384: Verify EnumComboBox deprecationThe AI-generated summary mentions that the
EnumComboBoxclass has been marked as deprecated with a warning to usesuperqt.QEnumComboBoxinstead. However, this change is not visible in the provided code snippet. Could you please verify if this change has been implemented?To confirm the implementation of the deprecation warning for the
EnumComboBoxclass, please run the following script:If the deprecation warning has been implemented, we should see it in the
__init__method of theEnumComboBoxclass.package/PartSegCore/analysis/save_functions.py (1)
Line range hint
1-431: Summary: Type hint updates for Python 3.9+ compatibilityThe changes in this file are focused on updating type hints to use the built-in
listtype instead oftyping.List. These updates are consistent with the PR objective of dropping Python 3.8 support and improve code readability. No functional changes or logic alterations were introduced.Key points:
- Updated parameter type in
save_projectfunction (line 38)- Updated return type in
get_fieldsmethod ofSaveProfilesToJSONclass (line 401)These changes contribute to modernizing the codebase for Python 3.9+ compatibility while maintaining the existing functionality.
package/PartSeg/_roi_mask/stack_settings.py (6)
Line range hint
25-32: LGTM: Updated type annotation forsave_locations_keysThe change from
typing.ClassVar[typing.List[str]]totyping.ClassVar[list[str]]is correct and aligns with the goal of using built-in type annotations available in Python 3.9+. This update maintains the same functionality while modernizing the type hinting.
39-39: LGTM: Updated type annotation forcomponents_parameters_dictThe change from
typing.Dict[int, ROIExtractionProfile]todict[int, ROIExtractionProfile]is correct and aligns with the goal of using built-in type annotations available in Python 3.9+. This update maintains the same functionality while modernizing the type hinting.
Line range hint
89-101: LGTM: Updated return type annotation forchosen_componentsmethodThe change from
typing.List[int]tolist[int]as the return type annotation is correct and aligns with the goal of using built-in type annotations available in Python 3.9+. This update maintains the same functionality while modernizing the type hinting.
Line range hint
205-224: LGTM: Updated type annotations intransform_statemethodThe changes to the type annotations in the
transform_statemethod are correct:
new_roi_extraction_parameters:typing.Dict[int, typing.Optional[ROIExtractionProfile]]→dict[int, typing.Optional[ROIExtractionProfile]]list_of_components:typing.List[int]→list[int]These updates align with the goal of using built-in type annotations available in Python 3.9+. The functionality remains the same while modernizing the type hinting.
Line range hint
283-289: LGTM: Updated parameter type annotation forcompare_historymethodThe change from
typing.List[HistoryElement]tolist[HistoryElement]as the type annotation for thehistoryparameter is correct and aligns with the goal of using built-in type annotations available in Python 3.9+. This update maintains the same functionality while modernizing the type hinting.
Line range hint
1-337: Summary: Successful migration to built-in type annotationsThe changes in this file consistently update type annotations from
typing.Listandtyping.Dicttolistanddictrespectively. These modifications align perfectly with the PR objective of dropping Python 3.8 support and adopting features available in Python 3.9+.Key points:
- All changes are type annotation updates, with no functional modifications to the code.
- The updates improve code readability and adhere to modern Python practices.
- These changes make the codebase more future-proof and easier to maintain.
Overall, this is a clean and effective update that modernizes the type hinting in the
StackSettingsclass and related functions.package/PartSegCore/analysis/measurement_base.py (9)
3-3: LGTM: Updated import for IterableThe change from
typing.Iterabletocollections.abc.Iterableis appropriate and aligns with modern Python practices for Python 3.9+. This update is consistent with dropping support for Python 3.8.
60-60: LGTM: Updated type annotation in has_mask_componentsThe change from
Tupletotuplein the function signature is appropriate and consistent with modern Python type hinting practices. The function's logic remains intact, maintaining its original functionality.
68-68: LGTM: Updated type annotation in has_roi_componentsThe change from
Tupletotuplein the function signature is appropriate and consistent with the previous updates. It aligns with modern Python type hinting practices while maintaining the original functionality of the function.
128-128: LGTM: Updated type annotations in Leaf class methodsThe changes from
Dicttodictin the method signatures ofget_channel_num,_parameters_string,_plugin_info, andpretty_printare appropriate and consistent. These updates align with modern Python type hinting practices and improve code consistency across theLeafclass while maintaining the original functionality of each method.Also applies to: 157-157, 172-172, 185-185
272-272: LGTM: Updated type annotation in Node class methodThe change from
Dicttodictin theget_channel_nummethod signature of theNodeclass is appropriate and consistent with the previous updates. It aligns with modern Python type hinting practices while maintaining the original functionality of the method.
282-282: LGTM: Updated type annotation in Node.pretty_print methodThe change from
Dicttodictin thepretty_printmethod signature of theNodeclass is appropriate and consistent with the previous updates. It aligns with modern Python type hinting practices while maintaining the original functionality of the method.
328-328: LGTM: Updated type annotation in MeasurementEntry.get_channel_num methodThe change from
Dicttodictin theget_channel_nummethod signature of theMeasurementEntryclass is appropriate and consistent with the previous updates. It aligns with modern Python type hinting practices while maintaining the original functionality of the method.
343-343: LGTM: Updated type annotations in MeasurementMethodBase classThe changes in the
MeasurementMethodBaseclass are appropriate:
- The class variable
need_class_methodnow useslistinstead ofList.- The
calculate_propertymethod parametersroi_alternativeandroi_annotationnow usedictinstead ofDict.These updates align with modern Python type hinting practices and are consistent with the previous changes in the file. The functionality of the class and method remains intact.
Also applies to: 375-376
Line range hint
1-424: Overall assessment: Consistent and appropriate updatesThe changes in this file consistently update type annotations to use built-in types (e.g.,
list,dict,tuple) instead of theirtypingmodule counterparts (e.g.,List,Dict,Tuple). These modifications align well with the PR objective of dropping Python 3.8 support and adopting modern Python practices for Python 3.9+.All changes preserve the original functionality of the classes and methods while improving code consistency and readability. The updates are thorough and applied consistently throughout the file.
Great job on modernizing the type hints in this module!
package/PartSegCore/analysis/load_functions.py (10)
Line range hint
168-173: LGTM: Updated type hint to use built-inlistThe change from
typing.Listtolistfor theload_locationsparameter is correct and aligns with modern Python type hinting practices. This update is consistent with dropping support for Python 3.8 and using features available in Python 3.9+.
Line range hint
188-193: LGTM: Consistent type hint updateThe change from
typing.Listtolistfor theload_locationsparameter is correct and consistent with the previous updates. This change maintains the modernization of type hints throughout the codebase.
Line range hint
227-232: LGTM: Consistent type hint modernizationThe update from
typing.Listtolistfor theload_locationsparameter maintains consistency with previous changes and adheres to modern Python type hinting practices.
249-251: LGTM: Type hint update for consistencyThe change from
typing.List[str]tolist[str]for thefile_pathsparameter is correct and maintains consistency with the type hint modernization throughout the file.
Line range hint
266-271: LGTM: Consistent type hint updateThe change from
typing.Listtolistfor theload_locationsparameter maintains consistency with previous updates and adheres to modern Python type hinting practices.
Line range hint
300-304: LGTM: Type hint modernizationThe update from
typing.Listtolistfor theload_locationsparameter in theload_mask_projectfunction is correct and consistent with the overall type hint modernization in this file.
352-356: LGTM: Comprehensive type hint updateThe changes from
typing.Listtolistfor both theload_locationsparameter and the return type are correct and consistent with the overall type hint modernization in this file. These updates maintain consistency and adhere to modern Python type hinting practices.
378-382: LGTM: Consistent type hint modernizationThe changes from
typing.Listtolistfor theload_locationsparameter and fromtyping.Tupletotuplefor the return type are correct and consistent with the overall type hint modernization in this file. These updates maintain consistency and adhere to modern Python type hinting practices.
430-434: LGTM: Consistent type hint updateThe change from
typing.Listtolistfor theload_locationsparameter is correct and consistent with the overall type hint modernization in this file. This update maintains consistency and adheres to modern Python type hinting practices.
Line range hint
1-464: Summary: Successful type hint modernizationThis file has been successfully updated to use modern Python type hinting practices. All instances of
typing.Listhave been replaced withlist, andtyping.Tuplehas been replaced withtuple. These changes are consistent throughout the file and align with the PR objective of dropping Python 3.8 support.The updates improve code readability and modernize the codebase without introducing any functional changes or bugs. This modernization ensures compatibility with Python 3.9+ and adheres to current best practices for type hinting.
Great job on maintaining consistency throughout the file!
package/PartSegCore/io_utils.py (9)
66-66: LGTM: Updated type hint to modern syntaxThe change from
typing.List[str]tolist[str]aligns with modern Python type hinting practices and is consistent with dropping Python 3.8 support.
77-77: LGTM: Consistent type hint updateThe change from
typing.List[str]tolist[str]for theneed_functionsclass variable is consistent with modern Python type hinting practices and aligns with dropping Python 3.8 support.
126-126: LGTM: Consistent type hint updateThe change from
typing.List[str]tolist[str]for theneed_functionsclass variable in theLoadBaseclass is consistent with modern Python type hinting practices and aligns with dropping Python 3.8 support.
144-148: LGTM: Consistent type hint updates inloadmethodThe changes in the
loadmethod's type hints, including theload_locationsparameter and the return type, are consistent with modern Python type hinting practices. These updates align with dropping Python 3.8 support and maintain the method's functionality.
170-170: LGTM: Consistent type hint update inget_next_filemethodThe change from
typing.List[str]tolist[str]for thefile_pathsparameter in theget_next_filemethod is consistent with modern Python type hinting practices and aligns with dropping Python 3.8 support.
197-197: LGTM: Updated return type hint inload_metadata_partfunctionThe change in the return type hint of the
load_metadata_partfunction fromtyping.Tuple[typing.Any, typing.List[typing.Tuple[str, dict]]]totuple[typing.Any, list[tuple[str, dict]]]is consistent with modern Python type hinting practices and aligns with dropping Python 3.8 support.
221-221: LGTM: Consistent type hint updates in utility functionsThe changes in the return type hints for
find_problematic_entriesandfind_problematic_leafsfunctions fromtyping.List[typing.MutableMapping]tolist[typing.MutableMapping]are consistent with modern Python type hinting practices and align with dropping Python 3.8 support.Also applies to: 239-239
274-274: LGTM: Updated return type hint inopen_tar_filefunctionThe change in the return type hint of the
open_tar_filefunction fromtyping.Tuple[TarFile, str]totuple[TarFile, str]is consistent with modern Python type hinting practices and aligns with dropping Python 3.8 support.
Line range hint
1-524: Summary: Consistent type hint updates throughout the fileThe changes in this file primarily focus on updating type hints from
typing.Listtolistandtyping.Tupletotuple. These updates are consistent throughout the file and align with modern Python type hinting practices. The changes improve code readability and maintainability without introducing any functional changes or potential issues. This update is appropriate for dropping Python 3.8 support and moving towards more recent Python versions.package/PartSeg/plugins/napari_widgets/roi_extraction_algorithms.py (4)
67-68: LGTM: Improved type hintingThe update from
typing.List[str]tolist[str]aligns with modern Python type hinting practices (PEP 585). This change enhances readability and ensures forward compatibility with Python 3.9+, while maintaining the same functionality.
70-72: LGTM: Enhanced type hintingThe update from
typing.Dict[str, Layer]todict[str, Layer]follows modern Python type hinting practices (PEP 585). This change improves code readability and ensures forward compatibility with Python 3.9+, while preserving the original functionality.
157-158: LGTM: Improved type hintingThe update from
typing.Dict[str, ROIExtractionProfile]todict[str, ROIExtractionProfile]follows modern Python type hinting practices (PEP 585). This change enhances code readability and ensures forward compatibility with Python 3.9+, while preserving the original functionality of the property.
300-304: LGTM: Improved type hinting in constructorThe updates to the parameter type hints in the
__init__method ofProfilePreviewDialogclass align with modern Python type hinting practices (PEP 585):
profile_dict: typing.Dict[str, ROIExtractionProfile]toprofile_dict: dict[str, ROIExtractionProfile]algorithm_selection: typing.Type[AlgorithmSelection]toalgorithm_selection: type[AlgorithmSelection]These changes enhance code readability and ensure forward compatibility with Python 3.9+, while maintaining the original functionality of the constructor.
package/PartSeg/common_gui/multiple_file_widget.py (3)
106-107: LGTM: Improved type hintingThe update to the
get_filesmethod signature improves readability by using the more modern type hinting syntax introduced in PEP 585. This change is consistent with best practices for Python 3.9+ codebases.
117-120: LGTM: Consistent type hint improvementsThe updates to the
__init__method signature andself.state_dicttype hint are consistent with the modern type hinting syntax introduced in PEP 585. These changes improve code readability and maintain consistency throughout the codebase.
373-376: LGTM: Consistent type hint updateThe update to the
add_statesmethod signature maintains consistency with the modern type hinting syntax used throughout the file. This change aligns with PEP 585 and improves overall code readability.package/PartSegCore/utils.py (3)
271-271: LGTM: Type hint modernizationThe type hint for
_callback_dicthas been updated to use built-in typesdictandlistinstead oftyping.Dictandtyping.List. This change aligns with modern Python type hinting practices and improves readability without altering functionality.
408-409: LGTM: Return type hint modernizationThe return type hint for the
pop_errorsmethod has been updated to use built-in typeslistandtupleinstead oftyping.Listandtyping.Tuple. This change is in line with modern Python type hinting practices and improves code readability without altering the method's functionality.
271-271: Changes align with PR objectiveThe type hint updates in this file, specifically for
_callback_dictand thepop_errorsmethod, are consistent with the PR objective of dropping Python 3.8 support. These changes use the new syntax for type hints introduced in Python 3.9, which improves code readability and modernizes the codebase. The updates are minimal and don't introduce any functional changes, making this a low-risk modification that achieves the intended goal.Also applies to: 408-409
package/PartSeg/_roi_analysis/measurement_widget.py (5)
58-58: LGTM: Updated type hint to use built-inlistThis change from
List[MeasurementResult]tolist[MeasurementResult]aligns with modern Python type hinting practices. It improves code readability and is consistent with the PR objective of dropping Python 3.8 support, as this syntax is available in Python 3.9+.
118-120: LGTM: Consistent type hint updateThe return type hint update from
List[str]tolist[str]in theget_headermethod is consistent with the previous changes and the PR objective. This change maintains consistency across the codebase and aligns with modern Python type hinting practices.
124-125: LGTM: Consistent type hint updates throughout the fileThe return type hint update from
List[str]tolist[str]in theget_rowsmethod is consistent with the previous changes in this file and aligns with the PR objective. This change further maintains consistency across the codebase and adheres to modern Python type hinting practices.
317-317: LGTM: Consistent type hint update in method parameterThe type hint update for the
widgets_listparameter fromList[Tuple[QWidget, int]]tolist[tuple[QWidget, int]]in the_move_widgetsmethod is consistent with the previous changes in this file. This change maintains consistency across the codebase, improves readability, and aligns with the PR objective of using modern Python type hinting practices.
Line range hint
1-424: Summary: Consistent type hint updates throughout the fileThe changes in this file are part of the larger effort to modernize the codebase and drop support for Python 3.8. All modifications are related to updating type hints from
ListtolistandTupletotuple. These updates improve code readability, maintain consistency throughout the file, and align with best practices for Python 3.9+. No logical changes or potential issues were identified during the review.The updates in this file contribute positively to the overall objective of the PR, which is to remove support for Python 3.8 and modernize the codebase.
package/PartSeg/common_gui/main_window.py (5)
133-134: LGTM: Updated type hint forget_setting_classThe change from
Type[BaseSettings]totype[BaseSettings]aligns with modern Python type hinting practices. This update is consistent with the PR objective of dropping Python 3.8 support.
164-164: LGTM: Updated type hint forviewer_listThe change from
List[Viewer]tolist[Viewer]is in line with modern Python type hinting practices. This update supports the PR's goal of dropping Python 3.8 support.
222-223: LGTM: Updated return type hint forget_colormapsThe change from
List[Optional[colormap.Colormap]]tolist[Optional[colormap.Colormap]]is consistent with modern Python type hinting practices. This update supports the PR's objective of dropping Python 3.8 support.
267-268: LGTM: Updated parameter type hint forread_dropThe change from
List[str]tolist[str]for thepathsparameter is in line with modern Python type hinting practices. This update supports the PR's goal of dropping Python 3.8 support.
Line range hint
1-391: Summary: Consistent type hint updates throughout the fileThe changes in this file are focused on updating type hints from the
typingmodule to built-in types. These updates include:
- Changing
Type[BaseSettings]totype[BaseSettings]- Updating
List[T]tolist[T]in various locationsThese modifications align with the PR objective of dropping Python 3.8 support and adopting modern Python type hinting practices. The changes improve code readability and maintain consistency throughout the file. No functional changes were made, and the updates should not introduce any new issues or bugs.
package/PartSeg/common_gui/error_report.py (3)
261-263: LGTM: Type hint update aligns with modern Python practicesThe change from
typing.Union[Exception, typing.Tuple[Exception, typing.List]]totyping.Union[Exception, tuple[Exception, list]]is a good improvement. It simplifies the type hint by using built-in types (tuple and list) instead of typing module constructs, which is possible in Python 3.9+. This change aligns well with the PR objective of dropping Python 3.8 support and modernizing the codebase.
302-305: LGTM: Improved type hinting and code formattingThe type hint update from
typing.Dict[str, typing.Union[Exception, typing.List[typing.Tuple[str, dict]]]]todict[str, typing.Union[Exception, list[tuple[str, dict]]]]is a positive change. It simplifies the type annotation by using built-in types (dict, list, tuple) instead of typing module constructs, which is possible in Python 3.9+. This aligns well with the PR objective of dropping Python 3.8 support and modernizing the codebase.Additionally, the minor indentation adjustment improves code readability.
Line range hint
1-461: Summary: Successful modernization of type hintsThe changes in this file successfully update the type hints to use the more concise syntax available in Python 3.9+. This aligns perfectly with the PR objective of dropping Python 3.8 support. The updates improve code readability and maintainability without altering the functionality of the classes. These changes are part of a larger effort to modernize the codebase and leverage newer Python features.
package/tests/test_PartSeg/test_channel_control.py (5)
241-244: Improved signal waiting logicThe consolidation of multiple
qtbot.waitSignalcalls into a singlewithstatement using tuple unpacking enhances code readability and reduces redundancy. This change maintains the same functionality while adopting a more modern Python approach for handling multiple context managers.
247-250: Consistent improvement in signal waiting logicThis change follows the same pattern as the previous modification, consolidating multiple
qtbot.waitSignalcalls into a singlewithstatement. The consistency in applying this improvement throughout the test method is commendable.
304-307: Consistent improvement in signal waiting logic across test methodsThe consolidation of
qtbot.waitSignalcalls into a singlewithstatement is consistently applied in this test method as well. This change maintains the pattern established in previous test methods, contributing to overall code consistency and readability.
309-312: Continued consistency in signal waiting logic improvementThis change further reinforces the consistent application of the improved signal waiting pattern within the
test_image_view_integration_filtermethod. The systematic nature of these improvements across different test cases and methods is noteworthy.
Line range hint
1-441: Summary: Systematic improvement in test signal handlingThe changes made to this file represent a comprehensive and consistent refactoring of the signal waiting logic across multiple test methods. These modifications significantly enhance code readability and maintainability while preserving the original functionality of the tests.
Key points:
- The consolidation of multiple
qtbot.waitSignalcalls into singlewithstatements is applied systematically throughout the file.- The changes align with modern Python practices for handling multiple context managers.
- The consistency of the refactoring across different test methods is commendable.
To further improve the code, consider implementing a helper function for signal waiting, as suggested earlier. This would reduce code duplication and make the tests even more concise and maintainable.
Overall, these changes represent a positive step in improving the quality and readability of the test suite.
package/PartSeg/_roi_analysis/export_batch.py (2)
311-311: Approved: Modernized type hintingThe change from
typing.List[typing.Tuple[str, bool]]tolist[tuple[str, bool]]reflects a move towards using built-in type hints. This is a positive change that:
- Simplifies the code
- Aligns with modern Python type hinting practices (Python 3.9+)
- Maintains the same semantic meaning
This update improves code readability and is consistent with the PR's objective of dropping support for older Python versions.
Line range hint
1-580: Overall assessment: Positive improvementsThe changes in this file are well-aligned with the PR objectives:
- Modernizing type hints by using built-in types instead of the
typingmodule.- Enhancing function flexibility with the new
zenodo_urlparameter.These updates improve code readability and maintainability while maintaining backward compatibility. The changes are consistent and do not introduce any apparent issues or bugs.
package/PartSeg/common_gui/colormap_creator.py (8)
4-4: LGTM: Import changes align with modern Python practices.The changes to the import statements, including the addition of
Iterablefromcollections.abcand the removal oftypingimports, align with Python 3.9+ type hinting best practices. This improves code readability and reduces dependencies on thetypingmodule.
75-76: LGTM: Type hint updates in ColormapEdit class.The changes to the type hints for
color_listandposition_listin theColormapEditclass are consistent with the transition to using built-in types. This improves code readability while maintaining the same functionality.
491-491: LGTM: Type hint updates in ColormapList class.The changes to the type hints in the
ColormapListclass, includingcolormap_mapand_widget_dict, are consistent with the transition to using built-in types. This improves code readability while maintaining the same functionality.Also applies to: 498-498
519-519: LGTM: Return type hint update in get_selected method.The change to the return type hint in the
get_selectedmethod fromSet[str]toset[str]is consistent with the transition to using built-in types. This improves code readability while maintaining the same functionality.
530-530: LGTM: Return type hint update in blocked method.The change to the return type hint in the
blockedmethod fromSet[str]toset[str]is consistent with the transition to using built-in types. This improves code readability while maintaining the same functionality.
620-620: LGTM: Type hint updates in PColormapList class.The changes to the type hints in the
PColormapListclass, including thecontrol_namesparameter and return types forget_selectedandblockedmethods, are consistent with the transition to using built-in types. This improves code readability while maintaining the same functionality.Also applies to: 628-628, 635-635
688-688: LGTM: Type hint update in ColormapLoad class.The change to the type hint for the
load_locationsparameter in theColormapLoadclass fromList[Union[str, BytesIO, Path]]tolist[Union[str, BytesIO, Path]]is consistent with the transition to using built-in types. This improves code readability while maintaining the same functionality.
Line range hint
1-700: Summary: Successful transition to modern type hinting practices.The changes made throughout this file consistently update type hints from the
typingmodule to built-in types, aligning with Python 3.9+ best practices. This transition improves code readability, reduces dependencies on thetypingmodule, and maintains the same functionality. The updates cover various classes and methods, includingColormapEdit,ColormapList,PColormapList, andColormapLoad.These changes contribute to a more maintainable and future-proof codebase. Great job on implementing these improvements!
package/PartSegImage/image_reader.py (8)
129-131: LGTM: Type hint updates improve readabilityThe changes to use built-in types (
list) instead oftyping.Listalign with modern Python type hinting practices and improve code readability. These updates don't affect the runtime behavior of the code.
137-137: LGTM: Consistent type hint updateThe return type hint update for
_get_channel_infomethod is consistent with the earlier changes, using the built-inlisttype instead oftyping.List. This change improves consistency across the codebase.
172-172: LGTM: Consistent type hint update for method parameterThe type hint update for the
default_spacingparameter in theread_imagemethod is consistent with the earlier changes, using the built-intupletype instead oftyping.Tuple. This change maintains consistency across the codebase.
191-191: LGTM: Consistent type hint update for method return typeThe return type hint update for the
_reduce_obsolete_dummy_axesmethod is consistent with the earlier changes, using the built-intupletype instead oftyping.Tuple. This change maintains consistency across the codebase.
319-322: LGTM: Improved readability with restructured context managersThe restructuring of context managers using parentheses improves code readability and makes it easier to add more context managers in the future if needed. This change doesn't affect the functionality but enhances the code structure.
415-418: LGTM: Consistent type hint updates for method parameter and return typeThe type hint updates for the
channelsparameter and return type of the_search_for_filesmethod are consistent with the earlier changes, using the built-inlisttype instead oftyping.List. These changes maintain consistency across the codebase.
510-512: LGTM: Improved type specificity for list comprehensionThe updated type hint for the
poslist comprehension provides more specific type information, usingtyping.Union[slice, int]. This change improves type checking and makes the code's intent clearer without affecting its functionality.
Line range hint
1-672: Summary: Consistent type hint updates and minor structural improvementsThe changes in this file primarily focus on updating type hints to use built-in types (e.g.,
list,tuple) instead oftypingmodule types (e.g.,List,Tuple). These updates improve code readability and align with modern Python type hinting practices. Additionally, there are minor structural improvements, such as the restructuring of context managers.These changes enhance type checking and code clarity without altering the existing functionality. The consistent application of these updates throughout the file maintains a uniform coding style.
package/PartSeg/_roi_analysis/batch_window.py (1)
77-77: LGTM! Type hint update improves compatibility.The change from
typing.Listtolistin the return type annotation is a positive update. This modification:
- Aligns with modern Python type hinting practices.
- Improves readability.
- Is consistent with the project's goal of dropping support for Python 3.8.
package/PartSegCore/mask/io_functions.py (5)
85-92: LGTM! Type hint updates improve readability.The changes to the type hints in the
MaskProjectTupleclass are consistent with modern Python practices. The transition fromtyping.Dicttodictandtyping.Listtolistenhances code readability without altering functionality. Thespacingattribute's type hint update totyping.Optional[list[float]]is also correct and more precise.
125-125: LGTM! Consistent type hint update.The change in the
spacingattribute's type hint fromtyping.List[float]tolist[float]is consistent with the updates made elsewhere in the file. This improves readability and aligns with modern Python type hinting practices.
Line range hint
339-343: LGTM! Consistent type hint update in method signature.The change in the
load_locationsparameter's type hint fromtyping.Listtolistis consistent with the previous updates in the file. This improves readability while maintaining the necessarytyping.Unionfor the complex type of the parameter. The functionality of the method remains unchanged.
Line range hint
377-381: LGTM! Consistent type hint update across classes.The change in the
load_locationsparameter's type hint is identical to the one made in the LoadROI class. This update maintains consistency across the codebase and improves readability while preserving the method's functionality.
717-717: LGTM! Consistent type hint update in method return type.The change in the
get_fieldsmethod's return type hint fromtyping.Listtolistis consistent with the previous updates in the file. This improves readability while maintaining the necessarytyping.Unionfor the complex return type. The functionality of the method remains unchanged.package/PartSegCore/analysis/calculation_plan.py (3)
301-301: LGTM: Updated type annotation for better readabilityThe change from
typing.List["CalculationTree"]tolist["CalculationTree"]is a good improvement. It simplifies the type annotation while maintaining the same meaning, which is in line with modern Python type hinting practices.
430-430: LGTM: Consistent type annotation updateThe change from
typing.List[str]tolist[str]for thefile_listattribute is consistent with the previous updates. This simplification of type annotations improves code readability while maintaining the same meaning.
552-552: LGTM: Consistent type annotation updateThe change from
typing.List[MeasurementCalculate]tolist[MeasurementCalculate]in the return type annotation of theget_measurementsmethod is consistent with the previous updates. This simplification improves code readability while maintaining the same meaning.package/PartSeg/common_gui/channel_control.py (12)
33-33: Type hint update looks good.The type hint for
ColorMapDicthas been updated fromtyping.Tupletotuple. This change aligns with modern Python type hinting practices and is consistent with the PR objective of dropping Python 3.8 support.
111-111: Type hint update is appropriate.The parameter type hint for
colorshas been updated fromtyping.List[str]tolist[str]. This change is in line with modern Python type hinting practices and consistent with the PR's objective.
157-157: Type hint update is consistent.The parameter type hint for
colorsin thechange_colorsmethod has been updated fromtyping.List[str]tolist[str]. This change maintains consistency with the earlier updates in the class.
302-302: Type hint update is appropriate and consistent.The type hint for
widget_dicthas been updated fromtyping.Dict[str, ColorComboBoxGroup]todict[str, ColorComboBoxGroup]. This change aligns with the previous updates and modern Python type hinting practices.
510-510: Type hint update is correct and consistent.The parameter type hint for
colorshas been updated fromtyping.Optional[typing.List[str]]totyping.Optional[list[str]]. This change is consistent with previous updates and correctly maintains the use oftyping.Optionalfor the nullable type.
527-527: Return type hint update is appropriate.The return type hint for the
selected_colormapsproperty has been updated fromtyping.List[Colormap]tolist[Colormap]. This change is consistent with the previous updates and accurately reflects the property's implementation.
536-536: Return type hint update is correct.The return type hint for the
channel_visibilityproperty has been updated fromtyping.List[bool]tolist[bool]. This change is consistent with the previous updates and accurately reflects the property's implementation.
544-544: Return type hint update is appropriate and consistent.The return type hint for the
current_colorsproperty has been updated fromtyping.List[typing.Optional[str]]tolist[typing.Optional[str]]. This change is consistent with previous updates and correctly maintains the use oftyping.Optionalfor potentially null values within the list.
556-556: Return type hint update is correct and consistent.The return type hint for the
current_colormapsproperty has been updated fromtyping.List[typing.Optional[Colormap]]tolist[typing.Optional[Colormap]]. This change is consistent with previous updates and correctly maintains the use oftyping.Optionalfor potentially null Colormap values within the list.
618-618: Return type hint update is appropriate and consistent.The return type hint for the
get_filtermethod has been updated fromtyping.List[typing.Tuple[NoiseFilterType, float]]tolist[tuple[NoiseFilterType, float]]. This change is consistent with the previous updates, replacing bothtyping.Listandtyping.Tuplewith their built-in equivalents.
637-637: Return type hint update is appropriate and consistent.The return type hint for the
get_gammamethod has been updated fromtyping.List[float]tolist[float]. This change is consistent with the previous updates in the file and aligns with modern Python type hinting practices.
Line range hint
1-737: Overall, type hint updates are consistent and improve code quality.The changes in this file focus on updating type hints from the
typingmodule to built-in types, which is in line with the PR objective of dropping Python 3.8 support. These updates improve code readability and align with modern Python practices. The changes are consistent throughout the file and do not introduce any functional modifications.A minor suggestion was made to further modernize union type hints if the minimum supported Python version allows it. Otherwise, all changes are approved and contribute positively to the codebase's quality and maintainability.
package/PartSeg/common_backend/base_settings.py (8)
9-9: LGTM: Import changes improve type hinting practices.The changes to the imports are good:
- Adding
Sequencefromcollections.abcprovides more flexibility in type hinting.- Removing
List,Dict, andTuplefromtypingis consistent with the transition to use built-in types for type hinting in Python 3.9+.These changes align with modern Python type hinting best practices.
Also applies to: 13-13
97-97: LGTM: Type hint updated to use built-in dict.The change in the return type annotation of the
additional_layersmethod fromDicttodictis consistent with the overall transition to use built-in types for type hinting. This update improves code readability and aligns with modern Python type hinting practices.
266-266: LGTM: Type hint updated to use built-in tuple.The change in the type annotation of
cached_labelsfromTupletotupleis consistent with the overall transition to use built-in types for type hinting. This update improves code readability and aligns with modern Python type hinting practices.
457-457: LGTM: Type hints updated to use built-in list.The changes in the type annotations of
save_locations_keysandhistoryfromListtolistare consistent with the overall transition to use built-in types for type hinting. These updates improve code readability and align with modern Python type hinting practices.Also applies to: 472-472
533-533: LGTM: Method type hints updated to use built-in list.The changes in the type annotations of
_load_files_call,set_history, andget_historymethods fromListtolistare consistent with the overall transition to use built-in types for type hinting. These updates improve code readability and align with modern Python type hinting practices.Also applies to: 567-567, 571-571
590-590: LGTM: File operation method type hints updated to use built-in types.The changes in the return type annotations of
get_save_list,get_path_history, andget_last_filesmethods fromListandTupletolistandtupleare consistent with the overall transition to use built-in types for type hinting. These updates improve code readability and align with modern Python type hinting practices.Also applies to: 598-598, 618-618
630-630: LGTM: Multiple file operation method type hints updated to use built-in types.The changes in the type annotations of
get_last_files_multipleandadd_last_files_multiplemethods fromListandTupletolistandtupleare consistent with the overall transition to use built-in types for type hinting. These updates improve code readability and align with modern Python type hinting practices.Also applies to: 633-633
Line range hint
1-805: Summary: Consistent update of type hints to use built-in types.The changes made in this file are part of a larger effort to update type hints from the
typingmodule to built-in types. This transition:
- Improves code readability.
- Aligns with modern Python type hinting practices.
- Prepares the code for better compatibility with Python 3.9+.
These changes do not alter the functionality of the code but enhance its maintainability and future-proofness. Great job on consistently applying these updates throughout the file!
package/PartSegImage/image.py (2)
17-18: LGTM: Type alias updates improve readability and compatibility.The changes to
Spacingand_IMAGE_DATAtype aliases are good improvements:
- Using
tupleinstead oftyping.Tupleis more concise and aligns with modern Python type hinting.- Changing
typing.Listtolistin_IMAGE_DATAfollows the same pattern and is consistent with the new syntax.These updates are in line with the PR objective of dropping Python 3.8 support and adopting more recent Python features.
Line range hint
216-220: LGTM: Updated type annotations in _adjust_channel_info method.The changes to the
_adjust_channel_infomethod are good improvements:
- The type hints for the
channel_infoparameter have been updated to use the new union syntax and include bothChannelInfoandChannelInfoFull.- The return type hint has been updated to use the more specific
list[ChannelInfoFull].- These changes are consistent with the updates made earlier in the file and improve type safety and clarity.
package/PartSegCore/analysis/batch_processing/batch_backend.py (1)
96-98: LGTM! Good update to modern type hinting.The changes from
ListandTupletolistandtuplealign with modern Python type hinting practices. This update improves code readability and consistency with newer Python versions. These changes don't affect runtime behavior but enhance static type checking capabilities.package/PartSeg/_roi_analysis/advanced_window.py (2)
5-5: LGTM: Improved import statementThe change to import only the necessary types from the
typingmodule is a good practice. It reduces namespace pollution and can slightly improve import times.
369-369: LGTM: Updated type hint to use built-in genericsThe type hint for
chosen_element_areahas been updated to use the built-intupletype instead ofTuplefrom thetypingmodule. This change aligns with PEP 585 and is a step towards more modern Python typing practices. It maintains the same meaning while reducing dependencies on thetypingmodule.package/PartSeg/common_gui/napari_image_view.py (13)
4-4: LGTM: Updated import statement follows best practices.The change from
typingtocollections.abcfor importingMutableMappingaligns with Python 3.9+ recommendations for type hinting.
9-9: LGTM: Removed unnecessary imports.The removal of
List,Dict, andTuplefrom the import statement is consistent with the transition to using built-in types for type hinting, which is part of the PR's objective.
117-117: LGTM: Updated type hint to use built-in types.The type hint for
ColorInfohas been updated to usedictandlistinstead ofDictandList, which aligns with the PR's objective of modernizing type hints.
123-124: LGTM: Consistent use of built-in types for type hinting.The type hints for
layersandfilter_infoattributes in theImageInfoclass have been updated to uselistinstead ofList, maintaining consistency with the PR's objective.
132-132: LGTM: Method signatures updated with built-in type hints.The
coords_inandtranslated_coordsmethod signatures in theImageInfoclass have been updated to uselistinstead ofListin their type hints, consistent with the PR's objective.Also applies to: 139-139
182-182: LGTM: Consistent use of built-in type for attribute type hint.The type hint for the
image_infoattribute has been updated to usedictinstead ofDict, maintaining consistency with the PR's objective of using built-in types for type hinting.
638-638: LGTM: Method signature updated with built-in type hint.The
calculate_filtermethod signature has been updated to usetupleinstead ofTuplein its type hint, consistent with the PR's objective of using built-in types for type hinting.
684-684: LGTM: Method signature updated with built-in type hint.The
_add_imagemethod signature has been updated to usetupleinstead ofTuplein its type hint, maintaining consistency with the PR's objective of using built-in types for type hinting.
772-772: LGTM: Return type hint updated with built-in types.The
images_boundsmethod signature has been updated to usetupleandlistinstead ofTupleandListin its return type hint, consistent with the PR's objective of using built-in types for type hinting.
988-988: LGTM: Return type hint updated with built-in type.The
_bounding_boxmethod signature has been updated to usetupleinstead ofTuplein its return type hint, maintaining consistency with the PR's objective of using built-in types for type hinting.
1073-1077: LGTM: Class attributes updated with built-in type hints.The type hints for multiple attributes in the
ImageParametersclass have been updated to uselistandtupleinstead ofListandTuple, consistent with the PR's objective of using built-in types for type hinting.
1081-1081: LGTM: Function signature updated with built-in type hint.The
_prepare_layersfunction signature has been updated to usetupleinstead ofTuplein its return type hint, maintaining consistency with the PR's objective of using built-in types for type hinting.
Line range hint
1-1136: Summary: Consistent update of type hints to use built-in types.This file has been systematically updated to use built-in types (
list,dict,tuple) instead of theirtypingmodule counterparts (List,Dict,Tuple) for type hinting. These changes are consistent with the PR's objective of dropping Python 3.8 support and modernizing the codebase. The updates maintain the existing functionality while improving compatibility with newer Python versions.Key points:
- Import statements have been updated to remove unnecessary imports from
typing.- Class attributes, method signatures, and function signatures have all been updated consistently.
- No functional changes were made, ensuring that the existing behavior of the code remains intact.
These changes contribute to a more modern and maintainable codebase.
package/PartSeg/_roi_analysis/prepare_plan_widget.py (6)
297-298: LGTM: Updated type hint to use built-inlist.The change from
typing.List[str]tolist[str]is a good modernization of the type hints, consistent with Python 3.9+ practices. This update improves code readability without changing the method's functionality.
305-306: LGTM: Consistent type hint update.The change from
typing.List[str]tolist[str]for thenew_valuesparameter is consistent with the previous update and modern Python type hinting practices. This change improves code consistency and readability.
320-321: LGTM: Type hint modernization for dictionary.The update from
typing.Dict[str, SaveBase]todict[str, SaveBase]forself.save_translate_dictis consistent with modern Python type hinting practices. This change improves code readability and maintains consistency with other type hint updates in the file.
643-644: LGTM: Consistent type hint update for set.The change from
typing.Set[str]toset[str]for themask_setparameter is in line with the previous updates and modern Python type hinting practices. This change maintains consistency throughout the codebase and improves readability.
693-694: LGTM: Consistent type hint update for dictionary.The change from
typing.Dict[str, SaveBase]todict[str, SaveBase]forself.save_translate_dictis consistent with the previous update in theOtherOperationsclass and modern Python type hinting practices. This change maintains consistency throughout the codebase and improves readability.
Line range hint
1-1252: Summary: Successful modernization of type hints.The changes made to this file consistently update type hints from the
typingmodule to use built-in types (e.g.,list,dict,set). These updates are in line with modern Python practices (Python 3.9+) and improve code readability. The changes don't affect the functionality of the code but do support the PR objective of dropping Python 3.8 support.Some key points:
- All updates are consistent throughout the file.
- The changes improve code readability and maintainability.
- These updates make the code compatible with newer Python versions while dropping support for Python 3.8.
Great job on modernizing the type hints in this file!
package/PartSegCore/analysis/measurement_calculation.py (13)
3-3: LGTM: Import and type hint updatesThe changes to imports and type hints are appropriate and align with modern Python practices. These updates improve type specificity and readability.
Also applies to: 94-96
84-84: LGTM: Updated type hint in ComponentsInfo classThe change from
Dict[int, List[int]]todict[int, list[int]]forcomponents_translationis consistent with the move towards using built-in types for type hinting. This update improves readability and aligns with modern Python practices.
110-111: LGTM: Updated type hints in MeasurementResult classThe changes to type hints for
_units_dictand_type_dictare appropriate, using built-in types instead of those from thetypingmodule. This update is consistent with the overall pattern in the file and improves readability.
160-160: LGTM: Updated return type hint in get_component_info methodThe change from
Tuple[bool, bool]totuple[bool, bool]for the return type hint ofget_component_infois appropriate and consistent with the move towards using built-in types for type hinting.
171-171: LGTM: Updated return type hint in get_labels methodThe change from
List[str]tolist[str]for the return type hint ofget_labelsis appropriate and consistent with the move towards using built-in types for type hinting.
189-189: LGTM: Updated return type hint in get_units methodThe change from
List[str]tolist[str]for the return type hint ofget_unitsis appropriate and consistent with the move towards using built-in types for type hinting.
235-235: LGTM: Updated return type hint in get_separated methodThe change from
List[List[MeasurementValueType]]tolist[list[MeasurementValueType]]for the return type hint ofget_separatedis appropriate and consistent with the move towards using built-in types for type hinting.
267-267: LGTM: Updated type hint in MeasurementProfile classThe change from
List[MeasurementEntry]tolist[MeasurementEntry]for thechosen_fieldsattribute is appropriate and consistent with the move towards using built-in types for type hinting.
287-287: LGTM: Updated return type hint in _get_par_component_and_area_type methodThe change from
Tuple[PerComponent, AreaType]totuple[PerComponent, AreaType]for the return type hint of_get_par_component_and_area_typeis appropriate and consistent with the move towards using built-in types for type hinting.
312-312: LGTM: Updated return type hint in get_channels_num methodThe change from
Set[Channel]toset[Channel]for the return type hint ofget_channels_numis appropriate and consistent with the move towards using built-in types for type hinting.
481-481: LGTM: Updated return type hint in calculate_tree methodThe change from
Tuple[Union[float, np.ndarray], symbols, AreaType]totuple[Union[float, np.ndarray], symbols, AreaType]for the return type hint ofcalculate_treeis appropriate and consistent with the move towards using built-in types for type hinting.
1561-1561: LGTM: Updated type hint in Haralick classThe change to use the built-in
dicttype for thehelp_dicttype hint is appropriate and consistent with the move towards using built-in types for type hinting.
Line range hint
1-1761: Summary: Consistent type hint updates throughout the fileThis pull request updates type hints throughout the
measurement_calculation.pyfile, transitioning from thetypingmodule to built-in types. These changes are consistent with modern Python practices and PEP 585. The modifications improve code readability without altering the existing functionality.Key points:
- All changes are non-functional and focus solely on type hint updates.
- The updates are consistent across various classes and methods in the file.
- These changes align with the stated objective of dropping Python 3.8 support, as the use of built-in types for type hinting is supported in Python 3.9+.
Overall, these changes represent a positive step towards modernizing the codebase and improving its maintainability.
package/PartSegCore/mask_create.py (1)
105-105: Use of built-in generic types in type annotationsThe updates to type annotations from
typing.List,typing.Dict, etc., to the built-in generic types likelistanddictare appropriate and align with the move to Python 3.9+. This modernizes the codebase and leverages Python's enhanced type hinting capabilities.Also applies to: 139-139, 154-154, 176-176, 232-232
package/PartSegCore/class_generator.py (1)
367-367: Ensure consistent usage of built-intuplefor type annotationsYou've updated the return type annotation of the
as_tuplemethod to use the built-intuple, which is appropriate now that support for Python 3.8 has been dropped. Please verify that all other instances oftyping.Tuplein the codebase have been updated totupleto maintain consistency.Run the following script to find any remaining usages of
typing.Tuple:package/PartSegCore/algorithm_describe_base.py (9)
9-9: ImportAnnotatedfromtypingModuleThe addition of
from typing import Annotatedis appropriate for utilizingAnnotatedtypes in the codebase, enhancing type annotations and metadata.
159-159: Update Type Annotation to Use Built-intypeThe type annotation for
__argument_class__has been updated fromtyping.Typeto the built-intype, which is acceptable since Python 3.9. This change modernizes the code and aligns with dropping support for Python 3.8.
187-187: Use Built-inlistin Return Type AnnotationThe return type of
get_fieldsis updated to use the built-inlistinstead oftyping.List, which is appropriate with the move to Python 3.9+.
207-207: Update Return Type to Built-indictThe method
get_fields_dictnow returnsdict[str, AlgorithmProperty]instead oftyping.Dict, leveraging built-in generic types available in Python 3.9 and later.
228-228: Modernize Return Type Annotation with Built-inlistThe function
get_fields_from_algorithmreturnslist[typing.Union[AlgorithmProperty, str]], using the built-inlisttype. This aligns with the updated Python version support.
241-241: UpdateTypeVarBound to Use Built-intypeThe
AlgorithmTypeTypeVar now uses the built-intypefor its bound (type[AlgorithmDescribeBase]), which is appropriate and modernizes the type hint.
295-295: Update Parameter Types to Use Built-inlistIn the
registermethod, theold_namesparameter now usestyping.Optional[list[str]]instead oftyping.Optional[typing.List[str]], updating to the built-inlisttype.
402-402: Use Built-indictin Type AnnotationThe
valuesattribute now utilizesdictin its type annotation:typing.Union[dict[str, typing.Any], PydanticBaseModel]. This change is consistent with replacingtyping.Dictwith the built-indict.
445-445: Update Method Signature with Built-in TypesThe
registerclass method inAlgorithmSelectionnow uses built-in types for theold_namesparameter, and the method signature reflects this modernization.package/PartSegCore/segmentation/restartable_segmentation_algorithms.py (3)
58-58: Type annotations updated to use built-indictUpdating the type annotation of
self.parametersto usedict[str, typing.Optional[typing.Any]]is appropriate now that support for Python 3.8 has been dropped. This change leverages the built-in generic types introduced in Python 3.9, improving readability and consistency across the codebase.
336-336: Type annotations updated to use built-indictIn the
cleanmethod, re-initializingself.parameterswith the type annotationdict[str, typing.Optional[typing.Any]]aligns with the updated usage of built-in generics. This ensures consistency and leverages Python 3.9 features throughout the code.
199-199: Ensure consistency of type annotations with parent classThe return type of the
get_additional_layersmethod has been updated todict[str, AdditionalLayerDescription]. Please verify that this change is consistent with any overridden methods in parent classes to ensure proper method overriding and type compatibility.To automate this verification, you can run the following shell script:
This script will help ensure that all implementations of
get_additional_layersin the inheritance chain use consistent type annotations.package/PartSeg/common_gui/algorithms_description.py (11)
Line range hint
285-292: Modernize return type annotation using built-intupleThe return type of the
get_getter_and_setter_functionmethod has been updated to use the built-intuplewith type parameters. This is appropriate and leverages the features available in Python 3.9+, improving code readability and consistency with modern Python standards.
Line range hint
323-327: Update constructor parameter type to use built-inlistIn the
FieldsListclass, the__init__method now uses the built-inlisttype for thefield_listparameter. This change enhances clarity and aligns with the updated type hinting practices following the removal of Python 3.8 support.
381-381: Modernize type alias with built-inlistandtypeThe
FieldAllowedTypestype alias has been updated to use built-inlistandtypeannotations. This modernization contributes to code clarity and takes advantage of the improvements in Python 3.9+.
511-511: Update type hint to use built-indictIn the
SubAlgorithmWidgetclass, thewidgets_dictattribute is now annotated withdict[str, FormWidget]. This change utilizes the built-indicttype, aligning with modern Python conventions and enhancing code readability.
562-564: Update return type annotation with built-indictThe
get_valuesmethod in theSubAlgorithmWidgetclass now returnsdict[str, typing.Any]. Using the built-indicttype improves clarity and follows the updated type hinting practices.
Line range hint
614-630: Use built-intypefor class type annotationsIn
BaseAlgorithmSettingsWidget, the__init__method now uses the built-intypefor thealgorithmparameter annotation. This modernizes the code and benefits from the syntactic improvements in Python 3.9+.
Line range hint
720-729: Update constructor type annotations inInteractiveAlgorithmSettingsWidgetThe
__init__method now uses built-intypeforalgorithmandlistforselector. This enhances code consistency and readability by utilizing modern type hinting features.
754-754: Annotatealgorithm_dictwith built-indictIn the
AlgorithmChooseBaseclass, thealgorithm_dictattribute is now annotated asdict[str, InteractiveAlgorithmSettingsWidget]. This change embraces modern type hinting practices for better code clarity.
756-762: Update constructor type annotations with built-intypeThe
__init__method ofAlgorithmChooseBasenow uses the built-intypefor thealgorithmsparameter. This aligns the code with Python 3.9+ standards and improves readability.
763-763: Initializealgorithm_dictwith updated type hintThe
algorithm_dictattribute is initialized withdict[str, BaseAlgorithmSettingsWidget]using the built-indicttype. This change modernizes the code and maintains consistency.
Line range hint
855-859: Update type annotations inAlgorithmChooseconstructorIn the
AlgorithmChooseclass, the__init__method now uses the built-intypefor thealgorithmsparameter. This update leverages Python 3.9+ features and enhances code clarity.package/PartSeg/_roi_mask/main_window.py (1)
890-892: Appropriate use of built-intypein type annotationChanging the return type annotation from
Type[StackSettings]totype[StackSettings]is correct and aligns with Python 3.9+ syntax. This update is consistent with dropping support for Python 3.8.
| @@ -1,5 +1,5 @@ | |||
| from abc import ABC | |||
| from typing import Callable, List, Optional, Tuple, Union | |||
| from typing import Callable, Optional, Union | |||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Consider using the | operator for union types
If the project now supports Python 3.10+, you could further modernize the type hints by using the | operator for union types. This would allow you to remove the Union import from typing. For example:
def get_fields_per_dimension(cls, image: Image) -> list[str | AlgorithmProperty]:
...This change would make the type hints more concise and align with the latest Python typing practices.
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.
Project is now 3.9+, not 3.10+
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.
@Czaki, understood. Since the project supports Python 3.9+, not 3.10+, the use of the | operator for union types isn't applicable at this time. Thank you for the clarification.
(_/)
(•ㅅ•)?
✏️ Learnings added
Learnt from: Czaki
PR: 4DNucleome/PartSeg#1206
File: package/PartSegCore/image_transforming/transform_base.py:2-2
Timestamp: 2024-10-09T13:08:00.211Z
Learning: The project supports Python 3.9+ but not 3.10+, so features introduced in Python 3.10 like the `|` operator for type annotations cannot be used.
Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
|
|
||
|
|
||
| def setup(app: Sphinx) -> Dict[str, Any]: | ||
| def setup(app: Sphinx) -> dict[str, Any]: |
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.
💡 Codebase verification
Type Hint Inconsistencies Found
There are remaining usages of typing.Dict in the following files:
package/PartSeg/_roi_mask/stack_settings.pypackage/PartSegCore/mask/io_functions.py
Please update these to use the built-in dict for type hinting to maintain consistency across the codebase.
🔗 Analysis chain
LGTM: Function signature updated correctly
The return type annotation of the setup function has been appropriately updated from Dict[str, Any] to dict[str, Any], aligning with the PR objective of using built-in types for type hinting.
To ensure consistency across the codebase, let's verify that similar changes have been made in other files:
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check for any remaining usage of typing.Dict in the codebase
# Test 1: Search for remaining imports of Dict from typing
echo "Checking for remaining 'from typing import Dict' statements:"
rg --type python "from typing import .*Dict"
# Test 2: Search for remaining usage of typing.Dict
echo "Checking for remaining usage of 'typing.Dict':"
rg --type python "typing\.Dict"
# Test 3: Verify that dict is being used as a type hint
echo "Verifying usage of 'dict' as a type hint:"
rg --type python " -> dict\["
# Note: If any of these tests return results, it may indicate inconsistencies in the type hint updates across the codebase.
Length of output: 550
Script:
#!/bin/bash
# Description: Check for any remaining usage of typing.Dict in the codebase
# Test 1: Search for remaining imports of Dict from typing
echo "Checking for remaining 'from typing import Dict' statements:"
rg --glob '*.py' "from typing import .*Dict"
# Test 2: Search for remaining usage of typing.Dict
echo "Checking for remaining usage of 'typing.Dict':"
rg --glob '*.py' "typing\.Dict"
# Test 3: Verify that dict is being used as a type hint
echo "Verifying usage of 'dict' as a type hint:"
rg --glob '*.py' " -> dict\["
# Note: If any of these tests return results, it may indicate inconsistencies in the type hint updates across the codebase.
Length of output: 2595
| roi_info: ROIInfo, | ||
| mask: typing.Optional[np.ndarray], | ||
| history: typing.List[HistoryElement], | ||
| history: list[HistoryElement], |
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.
💡 Codebase verification
Action Required: Remaining typing.List Usages Found
The following files still use typing.List. Please update these type hints to use the built-in list type to maintain consistency and adhere to the PR's objective of dropping Python 3.8 support:
package/PartSegCore/mask_create.pypackage/PartSeg/_roi_mask/stack_settings.pypackage/PartSegCore/analysis/calculation_plan.pypackage/PartSegCore/mask/io_functions.py
🔗 Analysis chain
LGTM: Updated type hint for Python 3.9+ compatibility.
The change from typing.List[HistoryElement] to list[HistoryElement] is consistent with the PR objective of dropping Python 3.8 support. This update improves readability by using the built-in list type.
To ensure consistency across the codebase, let's verify that similar changes have been made in other files:
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check for remaining usage of typing.List in the codebase
# Expect: No occurrences of 'typing.List'
rg --type python 'typing\.List'
Length of output: 64
Script:
#!/bin/bash
# Description: Check for remaining usage of typing.List in Python files
# Expect: No occurrences of 'typing.List'
rg --type py 'typing\.List'
Length of output: 989
| """ | ||
|
|
||
| correct_name: typing.ClassVar[typing.Dict[str, typing.Union[BaseModel, Enum]]] = { | ||
| correct_name: typing.ClassVar[dict[str, typing.Union[BaseModel, Enum]]] = { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
LGTM: Type annotation update with room for further improvement
The change from typing.Dict to dict in the correct_name class variable type annotation is consistent with the previous updates and improves readability.
However, we can further simplify this annotation:
Consider updating the type annotation to use the built-in Union type:
- correct_name: typing.ClassVar[dict[str, typing.Union[BaseModel, Enum]]] = {
+ correct_name: typing.ClassVar[dict[str, Union[BaseModel, Enum]]] = {This change requires adding Union to the imports from the typing module.
📝 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.
| correct_name: typing.ClassVar[dict[str, typing.Union[BaseModel, Enum]]] = { | |
| correct_name: typing.ClassVar[dict[str, Union[BaseModel, Enum]]] = { |
| return CalculationPlan(name=self.name, tree=deepcopy(self.execution_tree)) | ||
|
|
||
| def get_node(self, search_pos: typing.Optional[typing.List[int]] = None, parent=False) -> CalculationTree: | ||
| def get_node(self, search_pos: typing.Optional[list[int]] = None, parent=False) -> CalculationTree: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
LGTM: Type annotation update with room for further improvement
The change from typing.List[int] to list[int] in the search_pos parameter type annotation is consistent with the previous updates and improves readability.
However, we can further simplify this annotation if the project is using Python 3.10 or later:
Consider updating the type annotation to use the | operator for union types:
- def get_node(self, search_pos: typing.Optional[list[int]] = None, parent=False) -> CalculationTree:
+ def get_node(self, search_pos: list[int] | None = None, parent: bool = False) -> CalculationTree:This change makes the type annotation more concise and easier to read. Additionally, I've added a type annotation for the parent parameter.
Committable suggestion was skipped due to low confidence.
| def _cut_components( | ||
| mask: np.ndarray, image: np.ndarray, borders: int = 0 | ||
| ) -> typing.Iterator[typing.Tuple[np.ndarray, typing.List[slice], int]]: | ||
| ) -> typing.Iterator[tuple[np.ndarray, list[slice], int]]: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Consider updating typing.Iterator to Iterator from collections.abc
Since you're adopting built-in generic types, you might consider replacing typing.Iterator with Iterator from collections.abc for consistency and to utilize the built-in generics.
Add the import statement at the beginning of the file:
+from collections.abc import IteratorThen update the return type annotation of the _cut_components function:
-def _cut_components(
- mask: np.ndarray, image: np.ndarray, borders: int = 0
-) -> typing.Iterator[tuple[np.ndarray, list[slice], int]]:
+def _cut_components(
+ mask: np.ndarray, image: np.ndarray, borders: int = 0
+) -> Iterator[tuple[np.ndarray, list[slice], int]]:Committable suggestion was skipped due to low confidence.
| obj: type[BaseModel], | ||
| ) -> list[typing.Union[str, AlgorithmProperty]]: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Simplify Type Annotations by Importing Union Directly
In the functions base_model_to_algorithm_property_pydantic_1 and base_model_to_algorithm_property_pydantic_2, the return types use list[typing.Union[str, AlgorithmProperty]]. To enhance readability and maintain consistency, consider importing Union directly from typing and updating the annotations.
Apply this change:
-from typing import Annotated
+from typing import Annotated, Union
...
-def base_model_to_algorithm_property_pydantic_1(
- obj: type[BaseModel],
-) -> list[typing.Union[str, AlgorithmProperty]]:
+def base_model_to_algorithm_property_pydantic_1(
+ obj: type[BaseModel],
+) -> list[Union[str, AlgorithmProperty]]:
...
-def base_model_to_algorithm_property_pydantic_2(
- obj: type[BaseModel],
-) -> list[typing.Union[str, AlgorithmProperty]]:
+def base_model_to_algorithm_property_pydantic_2(
+ obj: type[BaseModel],
+) -> list[Union[str, AlgorithmProperty]]:Also applies to: 721-722
| def _pretty_print( | ||
| cls, values: typing.MutableMapping, translate_dict: typing.Dict[str, AlgorithmProperty], indent=0 | ||
| ): | ||
| def _pretty_print(cls, values: typing.MutableMapping, translate_dict: dict[str, AlgorithmProperty], indent=0): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Consider Replacing typing.MutableMapping with collections.abc.MutableMapping
The parameter values is annotated with typing.MutableMapping. Since we're updating to use built-in and standard library types, consider importing MutableMapping from collections.abc for consistency.
Apply this change:
-import typing
+from collections.abc import MutableMapping
...
-def _pretty_print(cls, values: typing.MutableMapping, translate_dict: dict[str, AlgorithmProperty], indent=0):
+def _pretty_print(cls, values: MutableMapping, translate_dict: dict[str, AlgorithmProperty], indent=0):Committable suggestion was skipped due to low confidence.
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
🧹 Outside diff range and nitpick comments (4)
tox.ini (2)
95-95: LGTM: Minimal requirements test environment updatedThe minimal requirements test environment has been correctly renamed from
py38-PyQt5-minimaltopy39-PyQt5-minimal, reflecting the new minimum supported Python version.Consider updating the comment for this section if it mentions Python 3.8 as the minimal version.
Line range hint
7-108: Summary: Comprehensive removal of Python 3.8 support from tox configurationThe changes in this file consistently remove Python 3.8 from all test environments, including:
- The main
envlist- Napari test environments
- Coverage test environments
- Minimal requirements test environment
- Azure Pipelines test environments
These modifications align perfectly with the PR objective of dropping support for Python 3.8 due to its EOL status. The changes ensure that all tests will now run on Python 3.9 and above, which is the new minimum supported version for the project.
To maintain consistency across the project, ensure that other configuration files (e.g.,
setup.py,pyproject.toml, CI configuration files) are also updated to reflect the new minimum Python version requirement.pyproject.toml (2)
35-35: LGTM: Python version requirement updatedThe change to require Python >=3.9 aligns with the PR objective to drop support for Python 3.8. This is a good update considering Python 3.8's end of life status.
Consider updating the
classifierssection to remove the Python 3.8 classifier if it exists.
Line range hint
180-236: Consider updating pytest configurationWhile the project has dropped support for Python 3.8, there don't appear to be any changes in the pytest configuration to reflect this update. It might be worth reviewing the pytest configuration to ensure it aligns with the new minimum Python version requirement.
Consider checking if there are any Python 3.8-specific pytest settings or markers that can be removed or updated.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (3)
- azure-pipelines.yml (1 hunks)
- pyproject.toml (5 hunks)
- tox.ini (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- azure-pipelines.yml
🧰 Additional context used
🔇 Additional comments (9)
tox.ini (4)
75-75: LGTM: Napari test environment updatedThe test environment for napari has been correctly updated to remove Python 3.8, maintaining consistency with the project's new minimum supported Python version.
89-89: LGTM: Coverage test environment updatedThe coverage test environment has been correctly updated to remove Python 3.8, aligning with the project's new minimum supported Python version.
108-108: LGTM: Azure Pipelines test environment updatedThe Azure Pipelines test environment has been correctly updated to remove Python 3.8, maintaining consistency with the project's new minimum supported Python version.
7-7: LGTM: Python 3.8 removed from test environmentsThe
envlisthas been updated to remove Python 3.8, which aligns with the PR objective of dropping support for this version. This change ensures that tests are only run on Python 3.9 and above.Let's verify that Python 3.8 has been consistently removed from other parts of the configuration:
pyproject.toml (5)
42-42: LGTM: Dependency versions updatedThe updates to dependency versions are appropriate and follow good practices:
- Most changes are minor version bumps, which typically introduce new features or bug fixes without breaking changes.
- The numpy dependency now has different version requirements for Python 3.10+ and <3.10, which helps maintain compatibility across different Python versions.
These updates should help keep the project current and potentially benefit from bug fixes and new features in the dependencies.
Please ensure that the project is compatible with these new versions, especially for dependencies with larger version jumps (e.g., imageio, pandas). Consider running the test suite with the updated dependencies to verify compatibility.
Also applies to: 49-49, 53-54, 56-57, 59-62, 67-67, 70-71, 74-74
130-130: LGTM: Optional dependencies updatedThe updates to the napari optional dependencies for PyQt6 and PySide6 are appropriate:
- Both now require napari>=0.5.0, which aligns with the general dependency updates in this PR.
- The use of specific Qt backend options (pyqt6 and pyside6_experimental) suggests careful consideration of compatibility.
Please ensure that the project is compatible with napari 0.5.0+ when using PyQt6 or PySide6. Consider testing these specific configurations to verify functionality.
Also applies to: 141-141
270-270: LGTM: Black configuration updatedThe update to Black's
target-versionfrom['py38']to['py39']is consistent with the project's new minimum Python version requirement. This ensures that Black will format the code according to Python 3.9 standards.
296-296: LGTM: Ruff configuration updatedThe update to Ruff's
target-versionfrom"py38"to"py39"is consistent with the project's new minimum Python version requirement. This ensures that Ruff will lint the code according to Python 3.9 standards.
Line range hint
1-391: Verify overall consistency with Python 3.9+ requirementThe changes in this file generally reflect the new minimum Python version of 3.9 and include consistent updates to dependencies. However, it's worth performing a final check to ensure all relevant sections have been updated.
Please review the entire file to confirm that:
- All references to Python 3.8 have been removed or updated where appropriate.
- All tool configurations (Black, Ruff, pytest, etc.) are consistent with the Python 3.9+ requirement.
- All dependencies are compatible with Python 3.9+.
This will help maintain consistency throughout the project configuration.
Codecov ReportAttention: Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## develop #1206 +/- ##
===========================================
- Coverage 93.13% 93.12% -0.01%
===========================================
Files 210 210
Lines 33149 33149
===========================================
- Hits 30873 30870 -3
- Misses 2276 2279 +3 ☔ View full report in Codecov by Sentry. |
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
🧹 Outside diff range and nitpick comments (3)
package/PartSeg/_roi_mask/stack_settings.py (2)
205-215: LGTM: Updated type annotations intransform_statemethodThe type annotations for
new_roi_extraction_parametersandlist_of_componentsparameters have been updated to use the Python 3.9+ syntax. The corresponding docstring type hints have also been updated for consistency. These changes align with the PR objective and improve code readability while maintaining the same functionality.Minor suggestion: Consider updating the docstring for
new_roi_extraction_parametersto remove the word "typing" from the type hint, as it's no longer necessary with the new syntax::param dict[int, Optional[ROIExtractionProfile]] new_roi_extraction_parameters:
Line range hint
320-327: LGTM with suggestions: Updated type annotations inget_maskfunctionThe type annotation for the
selectedparameter has been updated to use the Python 3.9+ syntax, changing fromtyping.List[int]tolist[int]. This change aligns with the PR objective.Suggestions for improvement:
- Update the docstring type hint for
selectedto match the new annotation::param list[int] selected: list of selected components which should be masked as non segmentation area- Verify if the return type should always be
np.ndarray. If it can beNone, consider keepingOptional[np.ndarray]in the return type hint.package/PartSegCore/mask/io_functions.py (1)
497-497: LGTM! Consistent type hint updates with a minor suggestion.The changes from
typing.List[str]tolist[str]andtyping.List[typing.Union[str, BytesIO, Path]]tolist[typing.Union[str, BytesIO, Path]]are consistent with the updates made elsewhere in the file. These changes improve readability without affecting the methods' functionality.However, for complete consistency, consider updating the return type hint on line 512:
) -> typing.Union[ProjectInfoBase, list[ProjectInfoBase]]:to:
) -> typing.Union[ProjectInfoBase, list[ProjectInfoBase]]:This minor change would make the return type hint consistent with the parameter type hints.
Also applies to: 508-508, 512-512
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (6)
- package/PartSeg/_roi_mask/stack_settings.py (6 hunks)
- package/PartSegCore/algorithm_describe_base.py (13 hunks)
- package/PartSegCore/analysis/calculation_plan.py (6 hunks)
- package/PartSegCore/analysis/measurement_base.py (11 hunks)
- package/PartSegCore/mask/io_functions.py (12 hunks)
- package/PartSegCore/mask_create.py (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- package/PartSegCore/analysis/calculation_plan.py
- package/PartSegCore/analysis/measurement_base.py
- package/PartSegCore/mask_create.py
🧰 Additional context used
🔇 Additional comments (23)
package/PartSeg/_roi_mask/stack_settings.py (5)
Line range hint
25-32: LGTM: Updated type annotation forsave_locations_keysThe type annotation for
save_locations_keyshas been updated to use the Python 3.9+ syntax, replacingtyping.List[str]withlist[str]. This change is consistent with the PR objective and improves code readability while maintaining the same functionality.
39-39: LGTM: Updated type annotation forcomponents_parameters_dictThe type annotation for
components_parameters_dicthas been updated to use the Python 3.9+ syntax, replacingtyping.Dict[int, ROIExtractionProfile]withdict[int, ROIExtractionProfile]. This change aligns with the PR objective and enhances code readability while preserving the existing functionality.
Line range hint
89-101: LGTM: Updated return type annotation forchosen_componentsmethodThe return type annotation for the
chosen_componentsmethod has been updated to use the Python 3.9+ syntax, changing fromtyping.List[int]tolist[int]. This modification is in line with the PR objective and improves code consistency while maintaining the same functionality.
Line range hint
283-288: LGTM: Updated type annotation incompare_historymethodThe type annotation for the
historyparameter in thecompare_historymethod has been updated to use the Python 3.9+ syntax, changing fromtyping.List[HistoryElement]tolist[HistoryElement]. This modification is in line with the PR objective and improves code consistency while maintaining the same functionality.
Line range hint
1-341: Overall assessment: Type annotation updates are consistent and improve code readabilityThe changes in this file successfully update type annotations to use Python 3.9+ syntax, replacing
typing.Listandtyping.Dictwithlistanddictrespectively. These modifications align well with the PR objectives and enhance code readability without altering the existing functionality.A few minor suggestions have been made to improve consistency in docstrings. Once these are addressed, the changes in this file will be fully compliant with the PR objectives and modern Python practices.
package/PartSegCore/mask/io_functions.py (10)
72-73: LGTM! Type hint updates improve readability.The changes from
typing.Listtolistandtyping.Dicttodictare consistent with modern Python type hinting practices. These updates make the code more concise and easier to read without affecting functionality.Also applies to: 75-75, 85-87, 90-90, 92-92
125-125: LGTM! Consistent type hint update.The change from
typing.List[float]tolist[float]for thespacingattribute is consistent with the updates made elsewhere in the file. This change improves readability without affecting functionality.
339-339: LGTM! Consistent type hint update in LoadROI class.The change from
typing.List[typing.Union[str, BytesIO, Path]]tolist[typing.Union[str, BytesIO, Path]]for theload_locationsparameter is consistent with the updates made elsewhere in the file. This change improves readability without affecting the method's functionality.
377-377: LGTM! Consistent type hint update in LoadROIParameters class.The change from
typing.List[typing.Union[str, BytesIO, Path]]tolist[typing.Union[str, BytesIO, Path]]for theload_locationsparameter is consistent with the updates made elsewhere in the file. This change improves readability without affecting the method's functionality.
426-426: LGTM! Consistent type hint update in LoadROIImage class.The change from
typing.List[typing.Union[str, BytesIO, Path]]tolist[typing.Union[str, BytesIO, Path]]for theload_locationsparameter is consistent with the updates made elsewhere in the file. This change improves readability without affecting the method's functionality.
471-471: LGTM! Consistent type hint update in LoadStackImage class.The change from
typing.List[typing.Union[str, BytesIO, Path]]tolist[typing.Union[str, BytesIO, Path]]for theload_locationsparameter is consistent with the updates made elsewhere in the file. This change improves readability without affecting the method's functionality.
575-575: LGTM! Consistent type hint update in save_components function.The change from
typing.Type[BaseImageWriter]totype[BaseImageWriter]for thewriter_classparameter is consistent with the updates made elsewhere in the file. This change improves readability without affecting the function's functionality.
717-717: LGTM! Consistent type hint update in SaveParametersJSON class.The change from
typing.List[typing.Union[AlgorithmProperty, str]]tolist[typing.Union[AlgorithmProperty, str]]for the return type of theget_fieldsmethod is consistent with the updates made elsewhere in the file. This change improves readability without affecting the method's functionality.
733-733: LGTM! Consistent type hint updates in LoadROIFromTIFF class.The changes from
typing.List[typing.Union[str, BytesIO, Path]]tolist[typing.Union[str, BytesIO, Path]]for theload_locationsparameter andtyping.Union[ProjectInfoBase, typing.List[ProjectInfoBase]]totyping.Union[ProjectInfoBase, list[ProjectInfoBase]]for the return type are consistent with the updates made elsewhere in the file. These changes improve readability without affecting the method's functionality.Also applies to: 737-737
Line range hint
1-777: Summary: Type hint updates improve code readability and consistency.The changes in this file primarily involve updating type hints to use more modern Python syntax, specifically replacing
typing.Listandtyping.Dictwithlistanddict. These updates align with the PR objective of updating type annotations to use Python 3.9+ syntax.Key points:
- The changes improve code readability and consistency throughout the file.
- No functional changes were made to the code, ensuring that existing behavior is maintained.
- The updates are consistent across all classes and functions in the file.
These changes contribute to a more modern and maintainable codebase without introducing any risks or altering the functionality of the code.
package/PartSegCore/algorithm_describe_base.py (8)
7-10: Appropriate Import Statements AddedThe imports of
MutableMappingfromcollections.abcandAnnotatedfromtypingare appropriate and align with the updated Python 3.9+ practices.
160-160: Updated Type Annotation for__argument_class__The type annotation for
__argument_class__has been updated totyping.Optional[type[PydanticBaseModel]], utilizing thetype[...]syntax introduced in Python 3.9. This modernizes the code and is appropriate given the updated minimum Python version.
208-208: Modernized Type Annotations inget_fields_dictThe return type annotation for
get_fields_dicthas been updated todict[str, AlgorithmProperty], embracing the built-in generics introduced in Python 3.9. This complies with the updated code style and improves readability.
242-242: UpdatedAlgorithmTypeTypeVar BoundThe
AlgorithmTypeTypeVar now has its bound updated totype[AlgorithmDescribeBase], utilizing thetype[...]syntax. This change correctly specifies thatAlgorithmTypeshould be a type that is a subclass ofAlgorithmDescribeBase.
296-296: Consistent Use of Built-in GenericsThe type annotation for
old_namesin theregistermethod has been updated totyping.Optional[list[str]], replacingtyping.Listwithlist. This aligns with the modernization efforts and maintains consistency in type annotations.
403-403: Modernized Type Annotations forvaluesThe type annotation for
valueshas been updated totyping.Union[dict[str, typing.Any], PydanticBaseModel], using the built-indictgeneric. This change is appropriate and improves code readability.
446-446: Updated Type Annotations in Class MethodregisterIn the
registerclass method, the type annotation forold_nameshas been updated totyping.Optional[list[str]], modernizing the code by using built-in generics.
539-539: Replacedtyping.MutableMappingwithMutableMappingfromcollections.abcThe type annotation for
valuesin_pretty_printhas been updated to useMutableMappingfromcollections.abc, reflecting the modernization and consistency with Python's standard library types.
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
🧹 Outside diff range and nitpick comments (1)
.github/workflows/upgrade-dependencies.yml (1)
Python 3.8 Specific Requirement Files Still Present
Python 3.8 specific requirement files are still present in the
requirements/directory. Please remove these files to fully drop support for Python 3.8.🔗 Analysis chain
Line range hint
38-42: LGTM: Python version update aligns with project objectivesThe removal of Python 3.8 from the dependency upgrade loop is consistent with the PR objective of dropping support for Python 3.8. This change ensures that dependency constraints are only generated for supported Python versions (3.9, 3.10, 3.11, and 3.12).
To ensure this change is consistent across the project, please run the following script:
This script will help identify any remaining references to Python 3.8 in configuration files, ensuring a consistent update across the project.
Please run the following script to comprehensively verify that Python 3.8 references have been removed across the project:
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify that Python 3.8 is not referenced in other configuration files # Check for Python 3.8 references in GitHub workflow files echo "Checking GitHub workflow files for Python 3.8 references:" rg --type yaml '3\.8' .github/workflows/ # Check for Python 3.8 references in setup files echo "Checking setup files for Python 3.8 references:" rg '3\.8' setup.py pyproject.toml # Check for Python 3.8 specific requirement files echo "Checking for Python 3.8 specific requirement files:" fd -e txt '.*3\.8.*' requirements/ # Check for Python 3.8 references in CI configuration echo "Checking CI configuration for Python 3.8 references:" fd -e yml -e yaml '(travis|appveyor|azure-pipelines)' | xargs rg '3\.8'Length of output: 647
Script:
#!/bin/bash # Description: Comprehensive verification to ensure Python 3.8 is not referenced in the codebase. echo "=== Checking GitHub workflow files for Python 3.8 references ===" rg --type yaml '3\.8' .github/workflows/ if [ $? -ne 0 ]; then echo "No Python 3.8 references found in GitHub workflow files." else echo "Python 3.8 references found in GitHub workflow files." fi echo "=== Checking setup files for Python 3.8 references ===" rg '3\.8' setup.py pyproject.toml if [ $? -ne 0 ]; then echo "No Python 3.8 references found in setup files." else echo "Python 3.8 references found in setup files." fi echo "=== Checking for Python 3.8 specific requirement files ===" fd -e txt '.*3\.8.*' requirements/ if [ $? -ne 0 ]; then echo "No Python 3.8 specific requirement files found." else echo "Python 3.8 specific requirement files found in requirements/." fi echo "=== Checking CI configuration for Python 3.8 references ===" fd -e yml -e yaml '(travis|appveyor|azure-pipelines)' | xargs rg '3\.8' if [ $? -ne 0 ]; then echo "No Python 3.8 references found in CI configuration files." else echo "Python 3.8 references found in CI configuration files." fiLength of output: 1261
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (6)
- .github/workflows/test_napari_widgets.yml (1 hunks)
- .github/workflows/tests.yml (5 hunks)
- .github/workflows/upgrade-dependencies.yml (1 hunks)
- requirements/constraints_py3.8.txt (0 hunks)
- requirements/constraints_py3.8_pydantic_1.txt (0 hunks)
- tox.ini (4 hunks)
💤 Files with no reviewable changes (2)
- requirements/constraints_py3.8.txt
- requirements/constraints_py3.8_pydantic_1.txt
🚧 Files skipped from review as they are similar to previous changes (2)
- .github/workflows/tests.yml
- tox.ini
🧰 Additional context used
🔇 Additional comments (2)
.github/workflows/test_napari_widgets.yml (1)
Line range hint
39-45: Update to napari versions looks good, but a few considerations:
The update to newer napari versions (419 and 54) aligns well with the PR objective of updating the codebase.
However, the inclusion of "napari417" in the matrix seems inconsistent with the update. Can you clarify why this older version is still being tested?
Given that the PR aims to drop Python 3.8 support, consider updating the Python version used in this job (currently 3.9 on line 47) to a more recent version, such as 3.10 or higher.
To ensure alignment with the PR objectives across the entire workflow:
.github/workflows/upgrade-dependencies.yml (1)
Line range hint
1-78: Summary: Workflow updated to reflect Python version changesThe changes made to this workflow file are minimal and focused, addressing only the Python version update by removing Python 3.8 from the dependency upgrade process. This change is consistent with the PR's objective of dropping support for Python 3.8.
The overall structure and functionality of the workflow remain intact, maintaining the existing jobs and steps for checking updated packages and creating pull requests.
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
🧹 Outside diff range and nitpick comments (2)
package/PartSeg/common_backend/python_syntax_highlight.py (2)
20-20: Approved: Good update to usesetFontFamiliesThe change from
setFontFamilytosetFontFamiliesis a good update, likely reflecting an API change in newer Qt versions. This new method allows for specifying multiple font families, which is beneficial for cross-platform compatibility.Consider adding fallback fonts for better cross-platform support. For example:
text_char_format.setFontFamilies(["monospace", "Courier", "Consolas"])This ensures that if "monospace" is not available on a system, it will fall back to "Courier" or "Consolas".
Line range hint
32-32: Consider addressing the TODO and updating external referencesThere's a TODO comment about supporting border style in the
get_text_char_formatfunction. Consider implementing this feature to enhance the highlighter's capabilities.Also, it might be worth checking if the external references (GitHub links in the comments) are still up-to-date and relevant. If they've changed or if there are newer, more relevant examples, updating these references could be beneficial for future maintenance.
Would you like assistance in implementing the border style support or researching updated external references?
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (5)
- .github/workflows/test_napari_widgets.yml (2 hunks)
- .github/workflows/tests.yml (5 hunks)
- package/PartSeg/common_backend/python_syntax_highlight.py (1 hunks)
- package/tests/conftest.py (1 hunks)
- tox.ini (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- .github/workflows/test_napari_widgets.yml
- .github/workflows/tests.yml
- tox.ini
🧰 Additional context used
🔇 Additional comments (4)
package/PartSeg/common_backend/python_syntax_highlight.py (1)
Line range hint
1-89: Overall, the file is well-structured and uses modern Python featuresThe code in this file is well-organized, uses modern Python features (like f-strings and
contextlib.suppress), and includes helpful comments. These aspects contribute to good readability and maintainability, which aligns well with the PR's objective of updating and improving the codebase.The changes made are appropriate and the overall quality of the code is high. Keep up the good work!
package/tests/conftest.py (3)
56-56: LGTM: Improved parameter naming in Image constructorThe change from
datatospacingas a named parameter in theImageconstructor improves code clarity by making the purpose of the argument explicit. This aligns well with Python's principle of explicit over implicit.
63-63: LGTM: Consistent parameter naming in Image constructorThe change from
datatospacingas a named parameter in thisImageconstructor call is consistent with the previous change. This maintains a uniform approach throughout the file and improves overall code clarity.
Line range hint
1-391: Summary: Consistent updates to Image constructor callsThe changes in this file are limited to two instances of updating the
Imageconstructor calls. Both modifications replace the unnameddataparameter with a namedspacingparameter. These changes:
- Improve code clarity by making the purpose of the argument explicit.
- Maintain consistency across the file.
- Align with the PR objectives of updating type annotations and refactoring for improved readability.
No issues were identified, and the changes appear to be part of a broader effort to enhance code quality and maintainability.
|
@coderabbitai full review |
✅ Actions performedFull review triggered. |
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: 16
🧹 Outside diff range and nitpick comments (74)
package/PartSegCore/image_transforming/transform_base.py (1)
21-21: LGTM: Return type hint updated correctlyThe change from
List[Union[str, AlgorithmProperty]]tolist[Union[str, AlgorithmProperty]]is consistent with modern Python typing practices for Python 3.9+. This update correctly uses the built-inlisttype instead of theListfrom thetypingmodule.For future consideration: When the project moves to Python 3.10+, you could further simplify this type hint by using the
|operator for union types, replacingUnion[str, AlgorithmProperty]withstr | AlgorithmProperty.package/PartSegCore/image_transforming/swap_time_stack.py (3)
17-17: LGTM! Consider updatingtyping.Optionalto|syntax.The change from
typing.Tupletotuplealigns with Python 3.9+ type hinting syntax and improves readability. Good job!For consistency, consider updating
typing.Optionalto use the|syntax introduced in Python 3.10. This would make the return type annotation:tuple[Image, ROIInfo | None]Similarly, you could update the
callback_functionparameter:callback_function: Callable[[str, int], None] | None = NoneThis change would further modernize the type hints and improve consistency across the codebase.
33-33: LGTM! Consider updatingtyping.Unionto|syntax.The change from
typing.Listtolistaligns with Python 3.9+ type hinting syntax and improves readability. Well done!For consistency and to further modernize the type hints, consider updating
typing.Unionto use the|syntax introduced in Python 3.10. This would make the return type annotation:list[AlgorithmProperty | str]This change would improve consistency across the codebase and take full advantage of the latest Python type hinting features.
Line range hint
1-33: Overall, good progress on modernizing type annotations.The changes in this file successfully update the type annotations to use Python 3.9+ syntax, improving code readability and maintaining consistency with modern Python practices. The lack of functional changes reduces the risk of introducing bugs.
To further improve the codebase, consider a comprehensive update of type annotations throughout the file:
- Update all occurrences of
typing.Optionalto use the|syntax (e.g.,str | None).- Update all occurrences of
typing.Unionto use the|syntax (e.g.,AlgorithmProperty | str).- Replace
typing.Callablewithcollections.abc.Callablefor better performance.These changes would make the type hints more consistent and take full advantage of the latest Python type hinting features. Here's an example of how the
transformmethod signature could look:from collections.abc import Callable # ... @classmethod def transform( cls, image: Image, roi_info: ROIInfo, arguments: dict, callback_function: Callable[[str, int], None] | None = None, ) -> tuple[Image, ROIInfo | None]: # ...Consider applying similar updates throughout the file and the rest of the codebase for consistency.
.github/workflows/test_napari_widgets.yml (1)
Line range hint
1-52: Summary of workflow changesThe updates to this workflow file effectively modernize the testing strategy for napari widgets:
- The latest release test now uses a more recent version of napari (napari54).
- The test matrix has been updated to include newer napari versions (napari419 and napari54).
- Backward compatibility testing is maintained for napari417 with the PySide2 backend.
These changes align well with the PR objective of updating dependencies and removing support for older Python versions. The workflow now focuses on more recent napari releases while still considering potential backward compatibility issues.
Consider implementing a strategy to automatically update these workflow files when new napari versions are released. This could involve using GitHub Actions to periodically check for new releases and create pull requests to update the workflow files.
package/PartSegCore/napari_plugins/save_tiff_layer.py (1)
28-28: LGTM: Function signature updated correctly.The changes to the
napari_write_imagesfunction signature are correct and align with the PR objective of updating type annotations to use Python 3.9+ syntax. TheListtype hint has been replaced withlistfor both thelayer_dataparameter and the return type.For consistency, consider updating the type hint for the
Optionalreturn type in thenapari_write_labelsfunction as well. You can replaceOptional[str]withstr | None.-def napari_write_labels(path: str, data: Any, meta: dict) -> Optional[str]: +def napari_write_labels(path: str, data: Any, meta: dict) -> str | None:package/PartSeg/common_gui/equal_column_layout.py (2)
15-15: LGTM! Consider adding an import for QLayoutItem.The update from
List[QLayoutItem]tolist[QLayoutItem]is correct and aligns with the PR objectives of using Python 3.9+ syntax for type annotations. This change improves readability and modernizes the code.As a minor suggestion, consider adding an explicit import for
QLayoutItemat the top of the file if it's not already imported in a shared module:from qtpy.QtWidgets import QLayout, QLayoutItemThis would make the code more self-contained and easier to understand.
Line range hint
1-83: Consider additional improvements for consistency and code quality.While the current changes are good, there are a few more areas where the code could be improved:
Add return type hints to all methods for consistency. For example:
def addItem(self, item: QLayoutItem) -> None:Consider refactoring the similar code in
deleteLaterand__del__to reduce duplication. You could create a helper method like:def _clean_up_items(self) -> None: for el in self._item_list: if el.widget(): el.widget().deleteLater() elif el.layout(): el.layout().deleteLater() self._item_list = []Then use this in both
deleteLaterand__del__.For better type checking, consider using
Optional[QLayoutItem]as the return type foritemAtandtakeAtmethods, as they can returnNone.Would you like me to provide a more detailed refactoring suggestion for these improvements?
package/PartSegCore/image_transforming/image_projection.py (1)
42-42: LGTM: Updated return type annotationThe change from
Tuple[Image, Optional[ROIInfo]]totuple[Image, Optional[ROIInfo]]is a good update, aligning with modern Python type hinting practices (Python 3.9+). This modification improves code readability without affecting the method's functionality.Consider updating the Python version in the project's
pyproject.tomlorsetup.pyto reflect the minimum supported version (3.9+) if not already done. This ensures consistency between the code and the project's metadata.package/PartSeg/common_backend/python_syntax_highlight.py (2)
20-20: LGTM! Consider adding a fallback font.The change from
setFontFamilytosetFontFamiliesis correct and aligns with modern Qt API. This update allows for specifying multiple fallback fonts, which can improve text rendering across different systems.Consider adding a fallback font to improve cross-platform compatibility. For example:
text_char_format.setFontFamilies(["monospace", "Courier", "Courier New"])This ensures that if "monospace" is not available, the system will try "Courier" and then "Courier New".
Line range hint
1-89: General suggestions for code improvementWhile not directly related to the changes in this PR, here are some suggestions to improve the overall quality of the file:
- Add docstrings to the
QFormatterandPylighterclasses to explain their purpose and usage.- Consider adding type hints to function parameters and return values for better code readability and maintainability.
- The comment "dirty, dirty hack" in the
highlightBlockmethod suggests that there might be a better way to handle this. Consider refactoring this part of the code in the future for a cleaner implementation.These suggestions are not critical for this PR but could be considered for future improvements.
package/PartSegCore/analysis/io_utils.py (1)
30-30: LGTM: Updated type hint to use Python 3.9+ syntaxThe change from
typing.Listtolistfor type hinting is correct and consistent with the previous change. This update improves code readability and aligns with modern Python syntax.For consistency, consider updating other type hints in this file that still use the
typingmodule, such astyping.Optionalon lines 31 and 34. This would further streamline the code and fully adopt the new syntax throughout the file.package/PartSegCore/sphinx/auto_parameters.py (1)
77-80: LGTM: Function signature updated correctlyThe return type annotation of the
setupfunction has been appropriately updated fromDict[str, Any]todict[str, Any], aligning with the PR objective of using built-in types for type hinting.Consider removing the unused
Dictimport from thetypingmodule at the beginning of the file.package/PartSeg/plugins/napari_widgets/utils.py (1)
Line range hint
1-89: Consider further type annotation improvements and function refactoring
Type Annotations:
Consider updatingtyping.Unionto use the|operator for union types in Python 3.10+. For example,typing.Union[QWidget, Widget]could be simplified toQWidget | Widget.
generate_imageFunction:
Thegenerate_imagefunction (lines 68-89) has complex logic that might benefit from refactoring or additional comments. Consider breaking it down into smaller, more focused functions or adding inline comments to explain the purpose of each step.Would you like assistance in implementing these suggestions?
.github/workflows/upgrade-dependencies.yml (1)
Line range hint
38-42: LGTM! Consider future-proofing the Python version list.The changes correctly remove Python 3.8 from the loop, aligning with the PR objective of dropping support for this version. This ensures that dependency constraints are only generated for supported Python versions (3.9 to 3.12).
To make future updates easier, consider using a variable to store the list of Python versions:
+PYTHON_VERSIONS="3.9 3.10 3.11 3.12" -for pyv in 3.9 3.10 3.11 3.12; do +for pyv in $PYTHON_VERSIONS; do uv pip compile --python-version ${pyv} --upgrade --output-file requirements/constraints_py${pyv}.txt pyproject.toml requirements/version_denylist.txt "${flags[@]}" uv pip compile --python-version ${pyv} --upgrade --output-file requirements/constraints_py${pyv}_pydantic_1.txt pyproject.toml requirements/version_denylist.txt "${flags[@]}" --constraint requirements/pydantic_1.txt doneThis approach would make it easier to add or remove Python versions in the future by modifying a single line.
package/PartSeg/plugins/modeling_save/save_modeling_data.py (1)
21-21: LGTM! Consider further simplifying the type annotation.The update from
typing.Listtolistaligns with modern Python type hinting practices for Python 3.9+. This change improves readability without affecting functionality.Consider further simplifying the type annotation by using
|instead oftyping.Unionfor Python 3.10+:def get_fields(cls) -> list[AlgorithmProperty | str]:This change would make the type hint even more concise and readable, assuming the project now targets Python 3.10 or later.
package/PartSeg/plugins/napari_widgets/colormap_control.py (1)
Line range hint
1-87: Consider further modernizing type annotations throughout the file.While the change on line 48 is correct and aligns with the PR objectives, there are opportunities to further modernize the type annotations throughout the file for consistency:
Update other type annotations to use built-in types where applicable. For example:
- Line 14:
Optional[Iterable[str]]could be changed toIterable[str] | None- Line 24: Consider using
list[QPushButton]instead ofList[QPushButton]if it's imported fromtypingUse
TypeAliasfor complex types that are used multiple times, improving readability and maintainability.Consider adding type annotations to method return values for improved type checking and documentation.
These changes would further align the entire file with modern Python typing practices and improve overall code consistency.
Would you like me to provide specific code examples for these suggestions?
package/PartSeg/plugins/napari_widgets/lables_control.py (1)
18-18: LGTM! Consider adding Python version comment.The change from
List[Sequence[float]]tolist[Sequence[float]]aligns with modern Python type hinting practices and improves readability. This is consistent with the PR objective of updating type annotations to use Python 3.9+ syntax.Consider adding a comment indicating the minimum Python version required for this syntax:
def __init__(self, viewer: Viewer, name: str, label: list[Sequence[float]], removable, parent=None): # Python 3.9+This can help developers quickly understand the version requirements when working with this code.
package/PartSeg/plugins/old_partseg/old_partseg.py (2)
67-67: LGTM! Consider further simplifying the type hint.The update from
typing.Listtolistaligns with Python 3.9+ type hinting syntax, improving readability and modernizing the code. This change is correct and doesn't affect the runtime behavior.Consider further simplifying the type hint by using
typing.Unionalias|:-load_locations: list[typing.Union[str, BytesIO, Path]], +load_locations: list[str | BytesIO | Path],This change would make the type hint even more concise and easier to read.
Line range hint
1-85: Consider modernizing additional type hints.While the current change correctly updates the
Listtype hint, there are opportunities to modernize other type hints in this file:
Replace
typing.Optionalwith the|syntax:range_changed: Callable[[int, int], Any] | None = NoneConsider creating a type alias for the complex union type used for
file_ob:FileType = str | tarfile.TarFile | TextIOBase | BufferedIOBase | RawIOBase | IOBase file_ob: FileType = load_locations[0]These changes would further improve code readability and maintain consistency with modern Python type hinting practices.
package/PartSeg/_launcher/check_version.py (1)
Line range hint
1-93: Consider enhancing error handling and user feedbackWhile the overall structure and functionality of the
CheckVersionThreadclass are sound, there are a few areas where we could potentially improve:
Error Handling: The broad exception handling in the
runmethod is good for capturing unexpected errors, but we might want to provide more specific handling for common issues (e.g., network errors).User Feedback: Consider adding a mechanism to inform the user when a version check fails, rather than silently failing.
Logging: Adding logging statements could help with debugging and monitoring the version check process.
Here's a suggestion for implementing these improvements:
import logging # ... (existing imports) logger = logging.getLogger(__name__) class CheckVersionThread(QThread): # ... (existing code) def run(self): if not state_store.check_for_updates: return try: # ... (existing code) except urllib.error.URLError as e: logger.warning(f"Failed to check for updates: {e}") self.network_error_signal.emit() # New signal to inform UI except json.JSONDecodeError: logger.error("Failed to parse version information") except Exception as e: logger.exception("Unexpected error during version check") with sentry_sdk.new_scope() as scope: # ... (existing error reporting code) # ... (rest of the class)These changes would provide more detailed error handling, improve logging, and allow for better user feedback in case of failures.
package/PartSegCore/roi_info.py (1)
80-80: LGTM: Type hint update aligns with modern Python syntax. Consider updating the docstring.The change from
Dict[int, BoundInfo]todict[int, BoundInfo]is in line with PEP 585 and the PR's objective to use Python 3.9+ syntax. This update improves readability without affecting the method's functionality.However, the docstring still mentions the return type as
Dict[int, BoundInfo]. Consider updating it to maintain consistency:@staticmethod def calc_bounds(roi: np.ndarray) -> dict[int, BoundInfo]: """ Calculate bounding boxes components :param np.ndarray roi: array for which bounds boxes should be calculated :return: mapping component number to bounding box :rtype: dict[int, BoundInfo] """ # ... rest of the methodpackage/PartSeg/common_gui/stack_image_view.py (1)
22-22: LGTM! Consider using|for union types.The update from
Listtolistis correct and aligns with the PR objectives of using Python 3.9+ syntax for type annotations. This change improves readability and simplifies the import structure.For even more modern Python type hinting (Python 3.10+), consider using the
|operator for union types:def __init__(self, settings: ViewSettings, image_view: list[ImageView] | ImageView):This change would require updating the minimum Python version to 3.10 in your project configuration.
package/PartSegCore/image_operations.py (2)
82-82: Great update to type annotation syntax.The change from
List[int]tolist[int]in themedianfunction signature aligns with Python 3.9+ type hinting practices. This update improves readability and is consistent with modern Python syntax.For consistency, consider updating similar annotations throughout the file. Here's a script to help identify other potential updates:
#!/bin/bash # Description: Find other instances of typing.List or typing.Dict that could be updated. # Test: Search for typing.List and typing.Dict usage rg --type python 'typing\.(List|Dict)' package/PartSegCore/image_operations.py
Line range hint
1-82: Overall assessment: Positive changes with room for further improvements.The changes in this file align well with the PR objectives, updating Python syntax for 3.9+ compatibility. The core functionality of the image processing operations remains intact, which is excellent.
To further improve the codebase:
- Consider applying similar type annotation updates throughout this file and the entire project for consistency.
- Review other import statements that might benefit from using
collections.abcinstead oftyping.- If not already done, update the project's minimum Python version requirement to 3.9 in the appropriate configuration files (e.g.,
setup.py,pyproject.toml).Would you like assistance in creating a plan or script to systematically update type annotations and imports across the project?
package/PartSegCore/project_info.py (1)
118-118: LGTM: Type annotation updated correctly, but docstring needs adjustment.The type annotation for the
componentsparameter has been properly updated to use the built-inlisttype instead ofListfrom thetypingmodule. This change aligns with the PR objective and is correct for Python 3.9+.However, the docstring for this function still mentions
List[int]in the parameter description. For consistency, it should be updated tolist[int].Consider updating the docstring as follows:
- :param Optional[List[int]] components: If present inform which components + :param Optional[list[int]] components: If present inform which components should be used when calculation mask, otherwise use all.package/PartSeg/_roi_mask/batch_proceed.py (3)
Line range hint
35-35: Consider updating type hint for consistencyThe type hint
Optional[None]forself.algorithmis unusual and can be simplified. Consider changing it to justNoneorOptional[ROIExtractionAlgorithm]if that's the intended type.Would you like assistance in updating this type hint?
Line range hint
54-54: Address the FIXME comment for therun_calculationmethodThere's a
# noqa: PLR0912 # FIXMEcomment indicating a known issue with therun_calculationmethod. This suggests that the method is too complex (PLR0912 is usually "Too many branches"). Consider refactoring this method to reduce its complexity.Would you like help in breaking down this method into smaller, more manageable functions?
Line range hint
54-115: Consider refactoring therun_calculationmethodThe
run_calculationmethod is quite long and complex, which can make it difficult to maintain and understand. Consider breaking it down into smaller, more focused methods. This could improve readability, testability, and make the code easier to maintain.Here's a suggested approach to refactor:
- Extract the file loading logic into a separate method.
- Create a method to handle the algorithm execution.
- Move the saving logic into its own method.
Would you like me to provide a more detailed refactoring plan or example code for this restructuring?
package/PartSeg/_launcher/main_window.py (2)
5-5: Consider removing unused importThe
typingmodule is imported on this line, but it appears to be used only for theTYPE_CHECKINGconstant. If this is the case, you might consider replacing this import with:from typing import TYPE_CHECKINGThis would make the import more specific and potentially improve import time slightly.
Line range hint
61-62: Address TODO commentsThere are two TODO comments in the file:
- On line 61-62: "TODO use more general solution for text wrapping"
- On line 145-146: "TODO understand qss overwrite mechanism"
These comments indicate areas that might need attention in the future. Consider creating issues to track these TODOs or addressing them in a future PR.
Also applies to: 145-146
package/PartSeg/common_gui/custom_save_dialog.py (1)
61-61: LGTM: Updated type annotation to use Python 3.9+ syntaxThe change from
typing.Optional[typing.List[str]]totyping.Optional[list[str]]in thehistoryparameter type annotation is correct and consistent with the PR's objective of updating to modern Python syntax.For further simplification, consider using the
|operator for union types introduced in Python 3.10+:history: list[str] | None = NoneThis would eliminate the need for
typing.Optionaland make the code even more concise..github/workflows/tests.yml (2)
58-72: LGTM: Include section updated appropriately.The
includesection has been updated to use newer Python versions for specific OS and Qt backend combinations. This change is consistent with dropping Python 3.8 support and aligns with the PR objectives.Consider adding a comment explaining the rationale behind the specific version choices for each combination to improve maintainability.
Line range hint
97-114: LGTM: Include and exclude sections updated appropriately.The
includesection has been updated to use newer Python versions for specific OS and Qt backend combinations. The addedexcludesection prevents testing unsupported combinations of Python versions and Qt backends. These changes are consistent with dropping Python 3.8 support and align with the PR objectives.Consider adding a comment explaining why Python 3.11 and 3.12 are excluded for PySide2 to improve clarity for future maintainers.
package/PartSeg/_roi_analysis/partseg_settings.py (2)
145-148: LGTM: Return type hint update forsegmentation_pipelinesThe change from
typing.Dict[str, SegmentationPipeline]todict[str, SegmentationPipeline]is correct and aligns with the PR objective of updating type annotations to use Python 3.9+ syntax. This change maintains the same functionality while using more modern Python type hinting.Good practice to keep the deprecation warning for backwards compatibility.
Consider adding a deprecation timeline or version in the warning message to help users plan for the eventual removal of this property.
154-161: LGTM: Return type hint updates forsegmentation_profilesandroi_profilesThe changes from
typing.Dict[str, ROIExtractionProfile]todict[str, ROIExtractionProfile]for both properties are correct and align with the PR objective of updating type annotations to use Python 3.9+ syntax. These changes maintain the same functionality while using more modern Python type hinting.Good practice to keep the deprecation warning for
segmentation_profilesfor backwards compatibility.Consider adding a deprecation timeline or version in the warning message for
segmentation_profilesto help users plan for the eventual removal of this property.package/PartSeg/common_gui/select_multiple_files.py (1)
89-89: Improve the class docstring forAddFiles.While adding a docstring is a good practice, the current docstring "Docstring for AddFiles." doesn't provide any meaningful information about the class's purpose or functionality. Consider expanding the docstring to include:
- A brief description of the class's purpose
- An overview of its main functionalities
- Any important attributes or methods
- Usage examples, if applicable
This will greatly improve the code's documentation and make it easier for other developers to understand and use the
AddFilesclass.package/PartSeg/common_gui/napari_viewer_wrap.py (1)
Line range hint
35-38: LGTM: Enhanced widget interactivity with checkbox-button connections.The new connections between checkboxes and buttons improve the widget's usability by disabling buttons when their corresponding checkboxes are unchecked. This prevents inconsistent UI states and enhances user experience.
For consistency, consider using a loop to set up these connections:
for chk, btn in [(self.sync_image_chk, self.sync_image_btn), (self.sync_ROI_chk, self.sync_ROI_btn), (self.sync_additional_chk, self.sync_additional_btn), (self.sync_points_chk, self.sync_points_btn)]: chk.stateChanged.connect(btn.setDisabled)This approach would make the code more maintainable and reduce repetition.
package/PartSegCore/segmentation/algorithm_base.py (2)
71-74: Great updates to type annotations.The changes from
Dicttodictin the type annotations are excellent. They align with modern Python type hinting practices and improve code readability. These updates are consistent across all dictionary type annotations in the class.Consider updating the docstring for the
ROIExtractionResultclass to reflect these changes in type annotations. This will ensure complete consistency throughout the class definition.
Line range hint
1-324: Overall excellent updates to modernize type annotations.The changes in this file consistently update type annotations from
Dicttodictand improve the import statement forMutableMapping. These modifications align the code with modern Python 3.9+ practices, enhancing readability and future compatibility. The updates are non-functional and don't introduce any potential issues or side effects.As you continue to modernize the codebase, consider the following suggestions for future improvements:
- Update other files in the project to use similar modern type annotations for consistency.
- Review and update docstrings throughout the codebase to reflect any changes in type annotations.
- Consider using more specific type hints where applicable, such as
dict[str, int]instead of justdict, to provide even more clarity about the expected types.package/PartSeg/common_gui/advanced_tabs.py (2)
239-239: LGTM: Updated type annotation and minor docstring suggestion.The change from
List[str]tolist[str]for theimage_view_namesparameter is consistent with the update in theColorControlclass and aligns with Python 3.9+ type hinting syntax.Consider updating the docstring to reflect the new type annotation:
""" Base class for advanced windows. It contains colormap management connected tabs: :py:class:`.PColormapCreator` and :py:class:`.PColormapList`. :param settings: program settings :param image_view_names: list of image view names passed to :py:class:`~.PColormapList` :param reload_list: optional list of reload functions :param parent: parent widget """
Action Required: Update remaining type annotations using
List[]andDict[]to built-in types.The following type annotations still use
List[]andDict[], which should be updated to use the built-inlistanddicttypes for consistency with Python 3.9+ syntax:
package/PartSegCore/project_info.py
:ivar List[HistoryElement] ~.history: history of calculation:param Optional[List[int]] components: If present inform which components
package/PartSegCore/mask/io_functions.py
:ivar typing.Optional[typing.List[float]] ~.spacing: information about spacing when image is missed.
package/PartSeg/common_gui/universal_gui_part.py
(List[(threshold, single_step)], default_single_step)(List[(threshold, single_step)], default_single_step)
package/PartSegCore/analysis/measurement_calculation.py
:ivar Dict[int, List[int]] components_translation: mapping
package/PartSegCore/analysis/batch_processing/batch_backend.py
- Multiple instances of
List[CalculationTree] children: list of nodes to iterate over...
package/PartSeg/_roi_mask/stack_settings.py
:param typing.List[int] selected: list of selected components which should be masked as non segmentation area
package/PartSegCore/roi_info.py
:ivar Dict[int,BoundInfo] bound_info: mapping from component number to bounding box:ivar Dict[int, Any] annotations: annotations of roi:ivar Dict[str, np.ndarray] alternative: alternative representation of roi:rtype: Dict[int, BoundInfo]
package/PartSegCore/segmentation/algorithm_base.py
:ivar Dict[str,AdditionalLayerDescription] ~.additional_layers: additional layers returned by algorithm.:ivar Dict[str,np.ndarray] alternative_representation: Arrays with alternative representations of ROI.Please update these annotations to use
listanddictinstead ofListandDict.🔗 Analysis chain
Line range hint
1-285: Verify consistency of type annotation updates across the project.The changes in this file are part of updating type annotations to use Python 3.9+ syntax. To ensure consistency across the entire project:
This script will help identify any remaining instances of
typing.Listandtyping.Dictthat may need to be updated for consistency.
Action Required: Correct the search commands to properly identify
typing.Listandtyping.Dictusages.To ensure that all instances of
typing.Listandtyping.Dictare accurately identified across the project, please execute the following updated shell script:🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for remaining usage of typing.List and typing.Dict # Test 1: Search for remaining usage of typing.List echo "Searching for remaining usage of typing.List:" rg --type python 'from\s+typing\s+import.*List' || echo "No remaining usage of typing.List found." # Test 2: Search for remaining usage of typing.Dict echo "Searching for remaining usage of typing.Dict:" rg --type python 'from\s+typing\s+import.*Dict' || echo "No remaining usage of typing.Dict found." # Test 3: Search for type annotations using List[] echo "Searching for type annotations using List[]:" rg --type python '\bList\[' || echo "No remaining usage of List[] in type annotations found." # Test 4: Search for type annotations using Dict[] echo "Searching for type annotations using Dict[]:" rg --type python '\bDict\[' || echo "No remaining usage of Dict[] in type annotations found."Length of output: 1107
Script:
#!/bin/bash # Description: Check for remaining usage of typing.List and typing.Dict # Test 1: Search for remaining usage of typing.List echo "Searching for remaining usage of typing.List:" rg -g "*.py" 'from\s+typing\s+import.*List' || echo "No remaining usage of typing.List found." # Test 2: Search for remaining usage of typing.Dict echo "Searching for remaining usage of typing.Dict:" rg -g "*.py" 'from\s+typing\s+import.*Dict' || echo "No remaining usage of typing.Dict found." # Test 3: Search for type annotations using List[] echo "Searching for type annotations using List[]:" rg -g "*.py" '\bList\[' || echo "No remaining usage of List[] in type annotations found." # Test 4: Search for type annotations using Dict[] echo "Searching for type annotations using Dict[]:" rg -g "*.py" '\bDict\[' || echo "No remaining usage of Dict[] in type annotations found."Length of output: 3245
package/PartSeg/_roi_analysis/profile_export.py (1)
Line range hint
1-379: Consider updating type hints throughout the file in a future PR.While the current changes are focused on the
ImportDialogconstructor and align with the PR objectives, it's worth noting that similar type hint updates could be applied to other parts of the file for consistency. This would involve replacingtyping.Dict,typing.List, andtyping.Typewith their built-in equivalents (dict,list, andtype) throughout the file.Examples of potential future updates:
- In the
ExportDialogclass, update parameter type hints.- In various method signatures, update return type hints.
- In type casting operations (e.g.,
typing.cast), update to use built-in types.These suggestions are for consideration in a future PR to maintain consistency across the codebase.
package/PartSegCore/analysis/save_functions.py (1)
401-401: LGTM: Updated return type hint for Python 3.9+ compatibility.The change from
typing.List[typing.Union[AlgorithmProperty, str]]tolist[typing.Union[AlgorithmProperty, str]]is consistent with the PR objective of dropping Python 3.8 support. This update improves readability by using the built-inlisttype.Consider using the
|operator for union types if the project targets Python 3.10+:def get_fields(cls) -> list[AlgorithmProperty | str]: return []This would further simplify the type hint and improve readability.
package/PartSeg/_roi_mask/stack_settings.py (2)
205-215: LGTM: Updated type annotations to use native Python syntax.The changes in the
transform_statemethod align with Python 3.9+ type hinting syntax:
- Parameter type annotations updated to use
dict[int, typing.Optional[ROIExtractionProfile]]andlist[int].- Corresponding docstring type annotations updated for consistency.
These updates improve code readability and consistency with modern Python practices without affecting functionality.
Consider updating the docstring for
new_roi_extraction_parametersto remove the line break for better readability:""" :param dict[int, typing.Optional[ROIExtractionProfile]] new_roi_extraction_parameters: Parameters used to extract roi """
Line range hint
320-341: LGTM: Updated parameter type annotation to use native Python syntax.The change from
typing.List[int]tolist[int]for theselectedparameter in theget_maskfunction aligns with Python 3.9+ type hinting syntax. This update improves code readability and consistency with modern Python practices without affecting functionality.Update the docstring to reflect the new type annotation:
""" :param list[int] selected: list of selected components which should be masked as non segmentation area """package/PartSegCore/io_utils.py (1)
197-197: LGTM: Type hint update inload_metadata_partfunctionThe return type hint has been updated from
typing.Tuple[typing.Any, typing.List[typing.Tuple[str, dict]]]totuple[typing.Any, list[tuple[str, dict]]], which is consistent with modern Python type hinting practices.Consider addressing the TODO comment in the function body:
# TODO extract to functionExtracting the logic to a separate function could improve code readability and maintainability.
package/PartSeg/plugins/napari_widgets/roi_extraction_algorithms.py (1)
86-87: LGTM: Updated type hint and consider adding test coverageThe change from
typing.Type[AlgorithmSelection]totype[AlgorithmSelection]is correct and consistent with the previous updates. It aligns with PEP 585 and improves code readability.Additionally, consider adding test coverage for this method, as it's currently marked with
# pragma: no cover.package/PartSeg/common_gui/multiple_file_widget.py (2)
117-120: Great job updating type hints consistently!The changes to
load_dictandself.state_dicttype hints are excellent, aligning with PEP 585 and improving code readability. For complete consistency, consider updating the return type hint ofdefaultdict(dict)on line 120 as well.Here's a suggested minor improvement:
- self.state_dict: dict[str, dict[str, ProjectInfoBase]] = defaultdict(dict) + self.state_dict: dict[str, dict[str, ProjectInfoBase]] = defaultdict[str, dict[str, ProjectInfoBase]](dict)This change would make the type hint fully consistent with the actual type of
defaultdict.
373-376: Excellent type hint update!The change from
List[ProjectInfoBase]tolist[ProjectInfoBase]is consistent with the modern type hinting style used throughout the file. This improves readability and maintains consistency.Consider updating the docstring to use the new type hint style as well:
- def add_states(self, states: list[ProjectInfoBase]): - """add multiple states to widget""" + def add_states(self, states: list[ProjectInfoBase]) -> None: + """Add multiple states to the widget. + + Args: + states (list[ProjectInfoBase]): List of project info states to add. + """This change would make the docstring more informative and consistent with the updated type hints.
package/PartSegCore/utils.py (1)
408-408: LGTM: Updated return type annotation enhances consistencyThe change from
typing.List[typing.Tuple[str, dict]]tolist[tuple[str, dict]]aligns with modern Python type hinting syntax (Python 3.9+). This update improves code readability and maintains consistency with the PR's objective.For even better consistency, consider updating the
dictpart of the return type totyping.Dictor justdict, depending on which style is preferred throughout the codebase.package/PartSeg/common_gui/colormap_creator.py (1)
9-10: Consider removing unused imports.The
ceilfunction from themathmodule and thePathclass from thepathlibmodule are imported but not used in the provided code. Consider removing these imports to keep the import statements clean and relevant.package/PartSegImage/image_reader.py (1)
Line range hint
129-418: Summary: Type annotation updates and minor structural improvementsThis pull request introduces several beneficial changes to the
image_reader.pyfile:
- Type annotations have been updated throughout the file to use built-in types (e.g.,
list,tuple) instead oftypingmodule types. This change aligns with modern Python type hinting practices (Python 3.9+).- The context manager structure in the
OifImagReaderclass has been improved for better readability.These changes enhance code readability and maintainability without altering the functionality. The updates are consistent and follow best practices for Python 3.9+.
Consider updating the project's minimum Python version requirement to 3.9+ in the project metadata and documentation to reflect these changes in type hinting syntax.
package/PartSegCore/mask/io_functions.py (4)
339-342: LGTM! Consider minor formatting adjustment.The type hint updates in the
loadmethod signature are consistent with the other changes in the file. However, to improve readability, consider adjusting the line breaks:@classmethod def load( cls, load_locations: list[typing.Union[str, BytesIO, Path]], range_changed: typing.Optional[typing.Callable[[int, int], typing.Any]] = None, step_changed: typing.Optional[typing.Callable[[int], typing.Any]] = None, metadata: typing.Optional[dict] = None, ) -> MaskProjectTuple:This format aligns the parameters and improves overall readability.
377-380: LGTM! Consider consistent formatting.The type hint updates in the
loadmethod signature are correct. For consistency with the previous suggestion, consider adjusting the line breaks:@classmethod def load( cls, load_locations: list[typing.Union[str, BytesIO, Path]], range_changed: typing.Optional[typing.Callable[[int, int], typing.Any]] = None, step_changed: typing.Optional[typing.Callable[[int], typing.Any]] = None, metadata: typing.Optional[dict] = None, ) -> MaskProjectTuple:This format aligns the parameters and improves overall readability, maintaining consistency throughout the file.
426-429: LGTM! Maintain consistent formatting.The type hint updates in the
loadmethod signature are correct. For consistency with the previous suggestions, consider adjusting the line breaks:@classmethod def load( cls, load_locations: list[typing.Union[str, BytesIO, Path]], range_changed: typing.Optional[typing.Callable[[int, int], typing.Any]] = None, step_changed: typing.Optional[typing.Callable[[int], typing.Any]] = None, metadata: typing.Optional[dict] = None, ) -> MaskProjectTuple:This format aligns the parameters and improves overall readability, maintaining consistency throughout the file.
471-474: LGTM! Ensure consistent formatting.The type hint updates in the
loadmethod signature are correct. For consistency with the previous suggestions, consider adjusting the line breaks:@classmethod def load( cls, load_locations: list[typing.Union[str, BytesIO, Path]], range_changed: typing.Optional[typing.Callable[[int, int], typing.Any]] = None, step_changed: typing.Optional[typing.Callable[[int], typing.Any]] = None, metadata: typing.Optional[dict] = None, ) -> MaskProjectTuple:This format aligns the parameters and improves overall readability, maintaining consistency throughout the file.
package/PartSegCore/analysis/calculation_plan.py (3)
430-430: Remove redundant type annotationThis type annotation for
file_listis redundant with the one already present in the class attribute definition on line 407. To maintain clean and DRY code, consider removing this line.- self.file_list: list[str] = file_list + self.file_list = file_list
505-505: LGTM: Type annotation update with room for further improvementThe change from
typing.Dicttodictin thecorrect_nameclass variable type annotation is consistent with the PR's goal of updating to Python 3.9+ syntax and improves readability.If the project supports Python 3.10+, consider further simplifying the annotation:
- correct_name: typing.ClassVar[dict[str, typing.Union[BaseModel, Enum]]] = { + correct_name: typing.ClassVar[dict[str, BaseModel | Enum]] = {This change would make the type annotation even more concise and easier to read.
591-591: LGTM: Type annotation update with room for further improvementThe change from
typing.List[int]tolist[int]in thesearch_posparameter type annotation is consistent with the PR's goal of updating to Python 3.9+ syntax and improves readability.If the project supports Python 3.10+, consider further simplifying the annotation:
- def get_node(self, search_pos: typing.Optional[list[int]] = None, parent=False) -> CalculationTree: + def get_node(self, search_pos: list[int] | None = None, parent: bool = False) -> CalculationTree:This change would make the type annotation more concise and easier to read. Additionally, I've added a type annotation for the
parentparameter.package/PartSegImage/image.py (3)
Line range hint
290-305: LGTM! Updated type annotations in Image class.The changes to the
Imageclass, particularly in the__init__method, improve type hinting and maintain consistency with the updated type aliases. This enhances code readability and type safety.Consider adding a type annotation for the
metadata_dictparameter in the__init__method for completeness:def __init__( self, data: _IMAGE_DATA, *, spacing: Spacing, file_path=None, mask: None | np.ndarray = None, channel_info: list[ChannelInfo | ChannelInfoFull] | None = None, axes_order: str | None = None, shift: Spacing | None = None, name: str = "", - metadata_dict: dict | None = None, + metadata_dict: dict[str, typing.Any] | None = None, ):This change would provide more specific type information for the
metadata_dictparameter.
Line range hint
1-1010: Overall, excellent updates to modernize type hinting!The changes in this file successfully modernize the type hinting throughout the
Imageclass and related components. These updates improve code readability, maintainability, and type safety without introducing significant functional changes. The use of newer Python features, such as the union type syntax (|), enhances the expressiveness of the type annotations.Consider the following architectural advice:
- Ensure that the minimum supported Python version is clearly documented, especially if using Python 3.10+ features like the union type syntax (
|).- If not already present, consider adding type checking to your CI pipeline (e.g., using mypy) to leverage these improved type annotations fully.
- As the
Imageclass is quite large, consider if any of its functionality could be split into separate, focused classes or modules to improve maintainability and separation of concerns.
Compatibility Issue: Union Type Syntax Requires Python 3.10+
The use of the union type syntax (
|) in theChannelInfoandChannelInfoFullclasses requires Python 3.10 or higher. However, the project specifies a minimum Python version of 3.9 inpyproject.toml. To ensure compatibility across supported Python versions, consider usingtyping.Unioninstead of the|operator.
- File: package/PartSegImage/image.py (Lines: 14-21)
🔗 Analysis chain
Line range hint
32-50: LGTM! Updated type annotations in ChannelInfo and ChannelInfoFull classes.The changes to
ChannelInfoandChannelInfoFullclasses improve type hinting by using the new union type syntax (|). This aligns with modern Python practices and enhances code readability.However, let's verify the minimum Python version supported by the project:
If the project supports Python versions lower than 3.10, consider using
typing.Unioninstead of the|operator for backward compatibility.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Check the minimum Python version in setup.py or pyproject.toml echo "Checking setup.py for Python version:" grep -n "python_requires" setup.py echo "Checking pyproject.toml for Python version:" grep -n "requires-python" pyproject.tomlLength of output: 286
package/PartSeg/_roi_analysis/advanced_window.py (1)
Outdated Type Hints Detected in Multiple Files
The verification scripts identified several instances where
ListandTupleare still imported from thetypingmodule and used in type hints across multiple.pyfiles. These outdated type hints should be updated to use Python’s built-in generics (e.g.,list,tuple) to ensure consistency and compatibility throughout the codebase.Additionally, the
mypystatic type checker is not installed, which limits our ability to perform comprehensive type checking.Recommended Actions:
- Update Type Hints: Replace all instances of
ListandTuplefrom thetypingmodule with built-inlistandtupletypes.- Install Static Type Checker: Consider installing
mypyor an alternative static analysis tool to facilitate ongoing type consistency and error detection.- Re-Run Verification Scripts: After making the above changes, re-execute the verification scripts to ensure all outdated type hints have been addressed.
🔗 Analysis chain
Line range hint
1-944: Verify compatibility with the rest of the codebase.While the changes in this file are limited to type hint updates and don't affect the runtime behavior, it's important to ensure that these updates are compatible with the rest of the codebase.
Run the following script to check for any potential issues:
Adjusting Verification Scripts for Compatibility Issues
The previous verification scripts encountered issues because the
rgcommand did not recognize thepythonfile type, andmypyis not installed in the sandbox environment.To address this, we'll modify the scripts to:
- Explicitly target
.pyfiles instead of relying on thepythonfile type.- Check for the availability of alternative static analysis tools or proceed without
mypyif it's not installable.</review_comment>
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for any incompatibilities or errors related to the updated type hints. # Test: Look for any imports of List or Tuple from typing module echo "Checking for outdated imports:" rg --type python 'from typing import .*?(List|Tuple)' # Test: Check if there are any remaining usages of List or Tuple from typing echo "Checking for remaining usage of typing.List or typing.Tuple:" rg --type python '\b(List|Tuple)\[' # Test: Run static type checker (if available) if command -v mypy &> /dev/null; then echo "Running mypy:" mypy package/PartSeg/_roi_analysis/advanced_window.py else echo "mypy not found. Consider installing and running a static type checker." fiLength of output: 526
Script:
#!/bin/bash # Description: Adjusted scripts to check for outdated typing imports and perform static type checking. # Test: Look for any imports of List or Tuple from typing module explicitly in .py files echo "Checking for outdated imports in .py files:" rg 'from typing import .*?(List|Tuple)' --glob '*.py' # Test: Check if there are any remaining usages of typing.List or typing.Tuple in .py files echo "Checking for remaining usage of typing.List or typing.Tuple in .py files:" rg '\b(List|Tuple)\[' --glob '*.py' # Test: Check if mypy is available, if not, suggest alternatives if command -v mypy &> /dev/null; then echo "Running mypy on advanced_window.py:" mypy package/PartSeg/_roi_analysis/advanced_window.py else echo "mypy not found. Skipping static type checking." echo "Consider installing mypy or using an alternative static analysis tool if available." fiLength of output: 2958
package/PartSegImage/channel_class.py (2)
Line range hint
6-8: Usepackaging.versionfor reliable version comparisonComparing version strings using
>=can lead to incorrect results because string comparisons may not accurately reflect version precedence (e.g.,"10.0.0" >= "2.0.0"evaluates toFalse). To ensure reliable version comparisons, usepackaging.version.parse.Apply this diff to fix the version comparison:
from importlib.metadata import PackageNotFoundError, version +from packaging.version import parse as parse_version from typing import TYPE_CHECKING, Union try: - PYDANTIC_2 = version("pydantic") >= "2.0.0" + PYDANTIC_2 = parse_version(version("pydantic")) >= parse_version("2.0.0") except PackageNotFoundError: # pragma: no cover PYDANTIC_2 = FalseThis change ensures that version comparisons are accurate and prevents potential bugs when newer versions of Pydantic are released.
83-85: Broaden the type annotation forjson_schemaThe current type annotation for
json_schemain__get_pydantic_json_schema__isdict[str, Union[str, dict]]. Given that the JSON schema can contain nested structures with various types (including lists and other dictionaries), this annotation might be too restrictive.Consider importing
Anyfromtypingand updating the type hint:+from typing import TYPE_CHECKING, Any ... def __get_pydantic_json_schema__(cls, core_schema: "CoreSchema", handler: "GetJsonSchemaHandler"): - json_schema: dict[str, Union[str, dict]] = {} + json_schema: dict[str, Any] = {} cls.__modify_schema__(json_schema) return json_schemaThis change acknowledges that the JSON schema can have values of any type, improving code clarity and avoiding potential type hinting issues.
package/PartSegCore/mask_create.py (4)
Line range hint
30-38: Fix attribute name typos in the__eq__method.In the
__eq__method of theMaskPropertyclass, there are typos in the attribute names when comparing withother. Specifically,other.clip_maskshould beother.clip_to_mask, andother.reverse_maskshould beother.reversed_mask. This could lead toAttributeErrorexceptions or incorrect equality checks.Apply this diff to correct the attribute names:
def __eq__(self, other): return ( isinstance(other, MaskProperty) and self.dilate == other.dilate and self.dilate_radius == other.dilate_radius and self.fill_holes == other.fill_holes and self.max_holes_size == other.max_holes_size - and self.clip_to_mask == other.clip_mask - and self.reversed_mask == other.reverse_mask + and self.clip_to_mask == other.clip_to_mask + and self.reversed_mask == other.reversed_mask )
Line range hint
85-89: Remove redundant__eq__method or consolidate equality logic.The
MaskPropertyclass defines an__eq__method inside the class and also defines an external functionmp_eqfor equality comparison, which is then assigned toMaskProperty.__eq__. Having both may lead to confusion or unintended behavior. Consider removing the original__eq__method within the class ifmp_eqis intended to replace it, or integrate the logic into a single method.
139-139: Consistent use of built-in generics in variable annotations.The type annotation for
sliceshas been updated to uselist[typing.Union[slice, int]], which is appropriate. Consider importingUniondirectly for improved readability, although this is optional.Optionally, you can simplify the import statement:
-import typing +from typing import Optional, UnionAnd update the annotation:
- slices: list[typing.Union[slice, int]] = [slice(None) for _ in range(mask.ndim)] + slices: list[Union[slice, int]] = [slice(None) for _ in range(mask.ndim)]
Line range hint
154-158: UseOptional[np.ndarray]instead oftyping.Union[None, np.ndarray].In the
_calculate_maskfunction, the type annotation forold_maskcan be simplified by usingOptional[np.ndarray]for clarity and consistency.Apply this diff to update the type annotation:
def _calculate_mask( mask_description: MaskProperty, dilate_radius: list[int], mask: np.ndarray, - old_mask: typing.Union[None, np.ndarray], + old_mask: Optional[np.ndarray], ) -> np.ndarray:Ensure that
Optionalis imported from thetypingmodule if not already done:+from typing import Optionalpackage/PartSegCore/algorithm_describe_base.py (1)
545-545: Increase Test Coverage for New Conditional BranchThe new conditional check at line 545 is not covered by existing tests. Consider adding unit tests to ensure this code path is tested.
Would you like assistance in writing a unit test for this branch?
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 545-545: package/PartSegCore/algorithm_describe_base.py#L545
Added line #L545 was not covered by testspackage/PartSegCore/segmentation/restartable_segmentation_algorithms.py (2)
58-58: Consider updating the type annotation todefaultdictfor accuracy.The variable
self.parametersis initialized as adefaultdict, but the type annotation specifiesdict[str, Optional[Any]]. For precise type hinting, consider annotating it asdefaultdict[str, Optional[Any]]from thecollectionsmodule.
336-336: Consider updating the type annotation todefaultdictfor accuracy.Similar to the initialization in the constructor,
self.parametersis re-initialized as adefaultdict. Updating the type annotation todefaultdict[str, Optional[Any]]would provide more accurate type information.package/PartSeg/_roi_mask/main_window.py (1)
Line range hint
58-58: Address theFIXME: Add tests forMaskDialog.There is a
# FIXME add testscomment indicating that tests are missing for theMaskDialogclass. To ensure the reliability and correctness of this component, it's important to implement unit tests.Would you like assistance in generating unit tests for
MaskDialog, or should I open a new GitHub issue to track this task?
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (82)
- .github/workflows/test_napari_widgets.yml (2 hunks)
- .github/workflows/tests.yml (5 hunks)
- .github/workflows/upgrade-dependencies.yml (1 hunks)
- azure-pipelines.yml (1 hunks)
- package/PartSeg/_launcher/check_version.py (1 hunks)
- package/PartSeg/_launcher/main_window.py (2 hunks)
- package/PartSeg/_roi_analysis/advanced_window.py (4 hunks)
- package/PartSeg/_roi_analysis/batch_window.py (2 hunks)
- package/PartSeg/_roi_analysis/export_batch.py (1 hunks)
- package/PartSeg/_roi_analysis/main_window.py (1 hunks)
- package/PartSeg/_roi_analysis/measurement_widget.py (3 hunks)
- package/PartSeg/_roi_analysis/partseg_settings.py (3 hunks)
- package/PartSeg/_roi_analysis/prepare_plan_widget.py (4 hunks)
- package/PartSeg/_roi_analysis/profile_export.py (1 hunks)
- package/PartSeg/_roi_mask/batch_proceed.py (3 hunks)
- package/PartSeg/_roi_mask/main_window.py (1 hunks)
- package/PartSeg/_roi_mask/segmentation_info_dialog.py (2 hunks)
- package/PartSeg/_roi_mask/stack_settings.py (6 hunks)
- package/PartSeg/common_backend/base_argparser.py (1 hunks)
- package/PartSeg/common_backend/base_settings.py (11 hunks)
- package/PartSeg/common_backend/partially_const_dict.py (2 hunks)
- package/PartSeg/common_backend/python_syntax_highlight.py (1 hunks)
- package/PartSeg/common_gui/advanced_tabs.py (2 hunks)
- package/PartSeg/common_gui/algorithms_description.py (10 hunks)
- package/PartSeg/common_gui/channel_control.py (11 hunks)
- package/PartSeg/common_gui/colormap_creator.py (8 hunks)
- package/PartSeg/common_gui/custom_load_dialog.py (4 hunks)
- package/PartSeg/common_gui/custom_save_dialog.py (2 hunks)
- package/PartSeg/common_gui/equal_column_layout.py (1 hunks)
- package/PartSeg/common_gui/error_report.py (2 hunks)
- package/PartSeg/common_gui/image_adjustment.py (2 hunks)
- package/PartSeg/common_gui/label_create.py (5 hunks)
- package/PartSeg/common_gui/main_window.py (5 hunks)
- package/PartSeg/common_gui/mask_widget.py (2 hunks)
- package/PartSeg/common_gui/multiple_file_widget.py (3 hunks)
- package/PartSeg/common_gui/napari_image_view.py (8 hunks)
- package/PartSeg/common_gui/napari_viewer_wrap.py (2 hunks)
- package/PartSeg/common_gui/numpy_qimage.py (1 hunks)
- package/PartSeg/common_gui/select_multiple_files.py (1 hunks)
- package/PartSeg/common_gui/stack_image_view.py (2 hunks)
- package/PartSeg/common_gui/universal_gui_part.py (2 hunks)
- package/PartSeg/plugins/modeling_save/save_modeling_data.py (1 hunks)
- package/PartSeg/plugins/napari_widgets/algorithm_widgets.py (2 hunks)
- package/PartSeg/plugins/napari_widgets/colormap_control.py (2 hunks)
- package/PartSeg/plugins/napari_widgets/lables_control.py (3 hunks)
- package/PartSeg/plugins/napari_widgets/roi_extraction_algorithms.py (5 hunks)
- package/PartSeg/plugins/napari_widgets/utils.py (1 hunks)
- package/PartSeg/plugins/old_partseg/old_partseg.py (1 hunks)
- package/PartSegCore/algorithm_describe_base.py (13 hunks)
- package/PartSegCore/analysis/analysis_utils.py (1 hunks)
- package/PartSegCore/analysis/batch_processing/batch_backend.py (2 hunks)
- package/PartSegCore/analysis/batch_processing/parallel_backend.py (5 hunks)
- package/PartSegCore/analysis/calculate_pipeline.py (2 hunks)
- package/PartSegCore/analysis/calculation_plan.py (6 hunks)
- package/PartSegCore/analysis/io_utils.py (1 hunks)
- package/PartSegCore/analysis/load_functions.py (9 hunks)
- package/PartSegCore/analysis/measurement_base.py (11 hunks)
- package/PartSegCore/analysis/measurement_calculation.py (18 hunks)
- package/PartSegCore/analysis/save_functions.py (2 hunks)
- package/PartSegCore/class_generator.py (1 hunks)
- package/PartSegCore/custom_name_generate.py (1 hunks)
- package/PartSegCore/image_operations.py (2 hunks)
- package/PartSegCore/image_transforming/combine_channels.py (3 hunks)
- package/PartSegCore/image_transforming/image_projection.py (2 hunks)
- package/PartSegCore/image_transforming/interpolate_image.py (3 hunks)
- package/PartSegCore/image_transforming/swap_time_stack.py (2 hunks)
- package/PartSegCore/image_transforming/transform_base.py (2 hunks)
- package/PartSegCore/io_utils.py (14 hunks)
- package/PartSegCore/mask/io_functions.py (12 hunks)
- package/PartSegCore/mask_create.py (6 hunks)
- package/PartSegCore/napari_plugins/loader.py (2 hunks)
- package/PartSegCore/napari_plugins/save_tiff_layer.py (2 hunks)
- package/PartSegCore/project_info.py (5 hunks)
- package/PartSegCore/register.py (1 hunks)
- package/PartSegCore/roi_info.py (4 hunks)
- package/PartSegCore/segmentation/algorithm_base.py (3 hunks)
- package/PartSegCore/segmentation/restartable_segmentation_algorithms.py (3 hunks)
- package/PartSegCore/sphinx/auto_parameters.py (2 hunks)
- package/PartSegCore/utils.py (2 hunks)
- package/PartSegImage/channel_class.py (2 hunks)
- package/PartSegImage/image.py (1 hunks)
- package/PartSegImage/image_reader.py (7 hunks)
⛔ Files not processed due to max files limit (15)
- package/PartSegImage/image_writer.py
- package/tests/conftest.py
- package/tests/test_PartSeg/test_channel_control.py
- package/tests/test_PartSeg/test_common_backend.py
- package/tests/test_PartSeg/test_common_gui.py
- package/tests/test_PartSegCore/segmentation/test_segmentation_algorithm.py
- package/tests/test_PartSegCore/test_algorithm_describe_base.py
- package/tests/test_PartSegCore/test_class_generator.py
- package/tests/test_PartSegCore/test_class_register.py
- package/tests/test_PartSegCore/test_io.py
- package/tests/test_PartSegCore/test_segmentation.py
- pyproject.toml
- requirements/constraints_py3.8.txt
- requirements/constraints_py3.8_pydantic_1.txt
- tox.ini
🧰 Additional context used
📓 Learnings (1)
package/PartSegCore/image_transforming/transform_base.py (1)
Learnt from: Czaki PR: 4DNucleome/PartSeg#1206 File: package/PartSegCore/image_transforming/transform_base.py:2-2 Timestamp: 2024-10-09T13:08:00.401Z Learning: The project supports Python 3.9+ but not 3.10+, so features introduced in Python 3.10 like the `|` operator for type annotations cannot be used.
🪛 GitHub Check: codecov/patch
package/PartSegCore/algorithm_describe_base.py
[warning] 545-545: package/PartSegCore/algorithm_describe_base.py#L545
Added line #L545 was not covered by tests
🔇 Additional comments (256)
package/PartSegCore/custom_name_generate.py (4)
3-3: LGTM: Import statement updated correctly.The import statement has been appropriately updated to only import
Anyfromtyping. This change is consistent with the PR objective of updating type annotations to use Python 3.9+ syntax, wheresetanddictcan be used directly for type hinting without importing fromtyping.
6-6: LGTM: Function signature updated to use Python 3.9+ type hinting syntax.The function signature has been correctly updated to use
set[str]anddict[str, Any]instead ofSet[str]andDict[str, Any]. This change aligns with the PR objective of updating type annotations to utilize modern Python syntax (3.9+). The semantic meaning of the type hints remains the same, while improving readability and consistency with current Python practices.
Line range hint
7-13: Consider minor improvements and clarify suppressed checks.The function logic appears sound and hasn't been changed in this PR. However, there are a few points to consider:
The error message in the RuntimeError could be more informative. Consider including the number of attempts made.
There are comments suppressing various checks (nosec, noqa: S311, NOSONAR). It would be helpful to understand why these checks are being suppressed and if they're still necessary.
Here's a suggested improvement for the error message:
- raise RuntimeError("Cannot generate proper names") # pragma: no cover + raise RuntimeError("Failed to generate a unique name after 1000 attempts") # pragma: no coverCould you please clarify the reasons for suppressing the security and code quality checks on line 10? Are these suppressions still necessary?
Line range hint
1-13: Summary: Type hint updates successfully implemented.The changes made to this file successfully update the type hints to use Python 3.9+ syntax, aligning with the PR objectives. The modifications improve code readability and maintain consistency with modern Python practices. The core functionality of the
custom_name_generatefunction remains unchanged, ensuring that existing behavior is preserved.While no significant issues were found, consider the suggested minor improvements to enhance error reporting and clarify the use of suppressed checks.
Overall, these changes contribute positively to the codebase by modernizing the type annotations without introducing new risks or altering the existing logic.
package/PartSegCore/image_transforming/transform_base.py (3)
2-2: LGTM: Import statement updated correctlyThe removal of
ListandTuplefrom the import statement is consistent with the changes in method signatures, moving towards using lowercase type hints. This change aligns with modern Python typing practices for Python 3.9+.
17-17: LGTM: Return type hint updated correctlyThe change from
Tuple[Image, Optional[ROIInfo]]totuple[Image, Optional[ROIInfo]]is consistent with modern Python typing practices for Python 3.9+. This update correctly uses the built-intupletype instead of theTuplefrom thetypingmodule.
Line range hint
1-28: Overall assessment: Changes are consistent and improve type hintingThe modifications in this file successfully update the type hints to align with Python 3.9+ syntax. The changes are consistent throughout the file, improving readability and maintaining the correct functionality. Great job on modernizing the type annotations while ensuring compatibility with the project's supported Python versions.
.github/workflows/test_napari_widgets.yml (1)
Line range hint
39-44: Approve update to napari versions in test matrix.The update to the napari versions in the test matrix (["napari419", "napari54"]) is appropriate and aligns with the PR objective of updating dependencies. The inclusion of "napari417" with "PySide2" suggests a strategy for maintaining some backward compatibility.
To ensure our testing strategy is comprehensive, please clarify:
- Is there a specific reason for maintaining compatibility with "napari417" only for the "PySide2" backend?
- Are there any known issues or dependencies that require testing this specific combination?
Consider running the following script to verify the existence and relevance of these napari versions:
#!/bin/bash # Description: Verify the existence and relevance of specified napari versions # Test: Check if the specified napari versions exist for version in "napari417" "napari419" "napari54"; do if gh release list --repo napari/napari | grep -q "${version#napari}"; then echo "$version exists" else echo "$version not found, consider updating or removing from the test matrix" fi done # Check for any deprecation notices or important changes gh issue list --repo napari/napari --label "deprecation" --limit 5package/PartSeg/common_gui/numpy_qimage.py (1)
8-8: Excellent update to modern type hinting!The change from
typing.Tupletotuplein theColorMapDicttype alias is a great improvement. This update:
- Aligns with PEP 585, allowing the use of built-in collection types in annotations.
- Improves code readability.
- Reduces the need for importing from the
typingmodule.- Is consistent with the PR objective of updating type annotations to use Python 3.9+ syntax.
This change is correct and beneficial for the codebase.
package/PartSegCore/analysis/analysis_utils.py (1)
29-29: Approved: Type annotation update aligns with modern Python practicesThe change from
typing.List[SegmentationPipelineElement]tolist[SegmentationPipelineElement]is a positive update. This modification:
- Aligns with the PR objective of updating type annotations to use Python 3.9+ syntax.
- Improves code readability by using the more concise built-in
listtype.- Maintains the same functionality while adopting modern Python practices.
Great job on keeping the codebase up-to-date with the latest Python standards!
package/PartSeg/common_gui/image_adjustment.py (1)
16-16: LGTM! Consider verifying consistent usage across the codebase.The update from
Dicttodictin the type hint is correct and aligns with the PR objective of using Python 3.9+ syntax for type annotations. This change doesn't affect the runtime behavior of the code.To ensure consistency across the codebase, please run the following script to check for any remaining usage of
typing.Dict:If the script finds any occurrences, consider updating them to use
dictinstead ofDictfor consistency.✅ Verification successful
Verified! No remaining usages of
Dictfrom thetypingmodule were found in the codebase. The type hint updates to usedictare consistent and correctly applied.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for remaining usage of typing.Dict in Python files # Test: Search for 'from typing import Dict' or 'from typing import ... Dict ...' echo "Checking for 'from typing import Dict':" rg --type python 'from\s+typing\s+import\s+(.*\s*,\s*)?Dict(\s*,|$)' # Test: Search for 'import typing' followed by 'typing.Dict' echo "Checking for 'typing.Dict' usage:" rg --type python -e 'import\s+typing' -e 'typing\.Dict'Length of output: 368
Script:
#!/bin/bash # Description: Check for remaining usage of typing.Dict in Python files # Test: Search for 'from typing import Dict' or 'from typing import ... Dict ...' echo "Checking for 'from typing import Dict':" rg --type py 'from\s+typing\s+import\s+(.*\s*,\s*)?Dict(\s*,|$)' # Test: Search for 'import typing' followed by 'typing.Dict' echo "Checking for 'typing.Dict' usage:" rg --type py 'import\s+typing' | rg 'typing\.Dict'Length of output: 297
Script:
#!/bin/bash # Description: Alternative method to check for remaining usage of typing.Dict in Python files # Find all Python files and search within them echo "Checking for 'from typing import Dict':" fd --type file --extension py | xargs rg 'from\s+typing\s+import\s+(.*\s*,\s*)?Dict(\s*,|$)' echo "Checking for 'typing.Dict' usage:" fd --type file --extension py | xargs rg 'typing\.Dict'Length of output: 330
package/PartSegCore/napari_plugins/save_tiff_layer.py (1)
2-2: LGTM: Import statement updated correctly.The removal of the
Listimport fromtypingaligns with the PR objective of updating type annotations to use Python 3.9+ syntax. This change is correct and consistent with modern Python practices.Let's verify that
Listis not used anywhere else in the file:package/PartSegCore/image_transforming/combine_channels.py (4)
2-2: LGTM: Import statement updated correctlyThe removal of the
Listimport from thetypingmodule is consistent with the changes in return type annotations and aligns with the PR objective of updating to Python 3.9+ syntax.
23-23: LGTM: Return type annotation updated correctlyThe return type annotation has been updated from
List[Union[str, AlgorithmProperty]]tolist[Union[str, AlgorithmProperty]], which is consistent with Python 3.9+ type annotation syntax. This change aligns with the PR objective of updating type annotations while maintaining the method's functionality.
40-40: LGTM: Return type annotation updated correctlyThe return type annotation has been updated from
Tuple[Image, Optional[ROIInfo]]totuple[Image, Optional[ROIInfo]], which is consistent with Python 3.9+ type annotation syntax. This change aligns with the PR objective of updating type annotations while maintaining the method's functionality.
Line range hint
1-58: Summary: Type annotations successfully updated to Python 3.9+ syntaxThe changes in this file successfully update the type annotations to use Python 3.9+ syntax, specifically:
- Removed the import of
Listfrom thetypingmodule.- Updated the return type annotation of
get_fields_per_dimensionfromListtolist.- Updated the return type annotation of
transformfromTupletotuple.These changes align perfectly with the PR objectives of dropping Python 3.8 support and updating type annotations to utilize modern Python syntax. The functionality of the code remains unchanged, ensuring a smooth transition to the newer Python versions.
package/PartSegCore/image_transforming/interpolate_image.py (3)
17-17: LGTM: Updated type annotation to use Python 3.9+ syntaxThe return type annotation has been correctly updated from
List[Union[str, AlgorithmProperty]]tolist[Union[str, AlgorithmProperty]]. This change aligns with the PR objective of using modern Python syntax for type annotations.
35-35: LGTM: Updated type annotation to use Python 3.9+ syntaxThe return type annotation has been correctly updated from
Tuple[Image, Optional[ROIInfo]]totuple[Image, Optional[ROIInfo]]. This change is consistent with the PR objective and improves code readability.
Line range hint
1-65: Summary: Successful update to modern Python type annotationsThe changes made to this file successfully update the type annotations to use Python 3.9+ syntax, replacing
ListandTuplewithlistandtuplerespectively. These modifications align with the PR objectives and improve code readability without altering the logic or functionality of theInterpolateImageclass.Key points:
- Type annotations in
get_fields_per_dimensionandtransformmethods have been updated.- The import of
ListandTuplefromtypinghas been removed.- No other changes were made to the file's logic or structure.
These updates contribute to the overall goal of dropping Python 3.8 support and modernizing the codebase.
package/PartSegCore/image_transforming/image_projection.py (1)
2-2: LGTM: Removed unused importThe removal of the
Tupleimport fromtypingis consistent with the transition to using the built-intupletype. This change improves code cleanliness by eliminating an unused import.package/PartSegCore/analysis/calculate_pipeline.py (4)
26-26: LGTM: Type hint update aligns with PR objectivesThe change from
typing.Dicttodictfor theadditional_layerstype hint is consistent with the PR's goal of updating type annotations to use Python 3.9+ syntax. This modification improves readability and adheres to modern Python practices without altering the underlying logic.
28-28: LGTM: Type hint update consistent with PR goalsThe change from
typing.Listtolistfor thehistorytype hint aligns perfectly with the PR's objective of updating type annotations to utilize Python 3.9+ syntax. This update enhances code readability and follows modern Python conventions without altering the underlying functionality.
57-57: LGTM: Return type hint update in line with PR objectivesThe modification of the return type hint from
typing.Tupletotuplefor thecalculate_segmentation_stepfunction is in perfect alignment with the PR's goal of updating type annotations to leverage Python 3.9+ syntax. This change enhances code readability and adheres to modern Python standards without altering the function's logic or behavior.
Line range hint
1-1: Consider removing unused importGiven that the type hints have been updated to use built-in types, it might be possible to remove the
import typingstatement if it's no longer used elsewhere in the file. This would further clean up the imports and align with the modernization efforts.To verify if the
typingimport is still necessary, you can run the following command:If this command returns no results (except for the import line itself), it's safe to remove the import.
package/PartSegCore/analysis/io_utils.py (1)
28-28: LGTM: Updated type hint to use Python 3.9+ syntaxThe change from
typing.Dicttodictfor type hinting is correct and aligns with the PR objective of updating to modern Python syntax. This change improves code readability and is consistent with dropping support for Python 3.8.package/PartSegCore/sphinx/auto_parameters.py (1)
Line range hint
1-80: Address remaining type hint inconsistenciesThe previous review identified type hint inconsistencies in other files. To maintain consistency across the codebase, please update the following files to use
dictinstead oftyping.Dict:
package/PartSeg/_roi_mask/stack_settings.pypackage/PartSegCore/mask/io_functions.pyLet's verify if these inconsistencies still exist:
✅ Verification successful
Re-verify usage of
typing.Dictin specified filesThe previous script encountered an error due to unrecognized file type. Please run the following commands to check for remaining usage of
typing.Dict:
No remaining usage of
typing.Dictfound in specified filesNo occurrences of
typing.Dictwere found in:
package/PartSeg/_roi_mask/stack_settings.pypackage/PartSegCore/mask/io_functions.py🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for remaining usage of typing.Dict in specific files echo "Checking for remaining usage of 'typing.Dict' in stack_settings.py:" rg --type python "typing\.Dict" package/PartSeg/_roi_mask/stack_settings.py echo "Checking for remaining usage of 'typing.Dict' in io_functions.py:" rg --type python "typing\.Dict" package/PartSegCore/mask/io_functions.pyLength of output: 512
Script:
#!/bin/bash # Description: Check for remaining usage of typing.Dict in specific files without specifying file type echo "Checking for remaining usage of 'typing.Dict' in stack_settings.py:" rg "typing\.Dict" package/PartSeg/_roi_mask/stack_settings.py echo "Checking for remaining usage of 'typing.Dict' in io_functions.py:" rg "typing\.Dict" package/PartSegCore/mask/io_functions.pyLength of output: 422
package/PartSeg/common_backend/partially_const_dict.py (4)
2-3: Excellent update to modern Python practices!The changes to the import statements are well-aligned with PEP 585, which recommends using standard collections instead of their typing counterparts. Importing
IteratorandMutableMappingfromcollections.abcand removing theDictimport fromtypingare good practices for Python 3.9+.
10-10: Great use of PEP 585 type hinting!The update of
RemovableInfotype alias fromTuple[T, bool]totuple[T, bool]is an excellent adoption of PEP 585. This change maintains the same functionality while using the more modern and concise syntax for generic type hints.
22-22: Excellent update to modern type hinting!The change in the type annotation for
const_item_dictfromClassVar[Dict[str, Any]]toClassVar[dict[str, Any]]is a great adoption of PEP 585. This update maintains the same functionality while using the more modern and concise syntax for generic type hints. The continued use ofClassVaris appropriate for this class-level variable.
Line range hint
1-85: Summary: Excellent modernization of type hintsThe changes made to this file are focused on updating type hints to use built-in types instead of their
typingmodule counterparts, in line with PEP 585. These updates include:
- Modifying import statements to use
collections.abcinstead oftypingforIteratorandMutableMapping.- Updating the
RemovableInfotype alias to usetupleinstead ofTuple.- Changing the type annotation for
const_item_dictto usedictinstead ofDict.These changes improve code readability and maintain compatibility with Python 3.9+, while preserving the original functionality of the
PartiallyConstDictclass. The consistent application of these updates throughout the file is commendable.package/PartSeg/plugins/napari_widgets/utils.py (1)
53-54: Approved: Type annotation update improves readabilityThe change from
typing.Type[FormWidget]totype[FormWidget]is a good improvement. It simplifies the type annotation by using the built-intypeinstead oftyping.Type, which is consistent with modern Python type hinting practices (Python 3.9+). This change enhances code readability while maintaining the same functionality.package/PartSeg/plugins/napari_widgets/colormap_control.py (1)
48-48: Type annotation update looks good.The change from
Dict[str, Tuple[Colormap, bool]]todict[str, tuple[Colormap, bool]]is consistent with the PR objectives of dropping Python 3.8 support and updating type annotations to use Python 3.9+ syntax. This modification aligns with PEP 585, which allows using built-in collection types in annotations.The change is also consistent with the removal of
DictandTupleimports from thetypingmodule at the beginning of the file.This update doesn't affect the functionality of the
NapariColormapListclass, as it's purely a type annotation change.package/PartSeg/plugins/napari_widgets/lables_control.py (2)
1-1: LGTM! Removal of unused import.The removal of the
Listimport fromtypingis consistent with the changes made to the type annotations in the file. This cleanup improves code clarity by removing unused imports.
Line range hint
1-90: Summary: Changes align with PR objectives, minor improvements suggested.The changes in this file successfully update the type annotations to use Python 3.9+ syntax, which aligns with the PR objectives. The modifications improve code readability and modernize the type hinting practices.
Key points:
- Type annotations have been updated from
List[Sequence[float]]tolist[Sequence[float]].- The
Listimport fromtypinghas been removed.- No functional changes were made to the code logic.
Suggestions for improvement:
- Add comments indicating the minimum Python version required for the new syntax.
- Fix the potential typo in the class name "NaparliLabelChoose".
Overall, the changes are well-implemented and achieve the intended goals of the PR.
package/PartSeg/_roi_mask/segmentation_info_dialog.py (3)
1-1: LGTM: Import statement updated correctlyThe removal of
Dictfrom the import statement is in line with the PR objective to update type annotations to Python 3.9+ syntax. The continued import ofOptionalandCallableis correct as these are still used in the type hints.
1-1: Overall impact: Successful modernization of type hintsThe changes in this file successfully modernize the type hints by updating the import statements and method signatures to use Python 3.9+ syntax. These modifications improve code readability and maintain consistency with modern Python practices without affecting the runtime behavior of the code. The changes align well with the PR objectives of updating type annotations and dropping support for Python 3.8.
Also applies to: 48-49
48-49: LGTM: Method signature updated correctlyThe change from
Dicttodictin the method signature is consistent with the PR objective to update type annotations to Python 3.9+ syntax. This change doesn't affect the functionality of the method.To ensure consistency across the codebase, let's verify that similar changes have been made in other files:
✅ Verification successful
All
typing.Dictusages have been successfully replaced withdict.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for any remaining usage of typing.Dict in the codebase # Test 1: Search for remaining imports of Dict from typing echo "Checking for remaining imports of Dict from typing:" rg --type python 'from typing import .*Dict' # Test 2: Search for remaining usage of typing.Dict echo "Checking for remaining usage of typing.Dict:" rg --type python 'typing\.Dict' # Test 3: Verify that dict is being used for type hinting echo "Verifying usage of dict for type hinting:" rg --type python '\bdict\['Length of output: 508
Script:
#!/bin/bash # Description: Corrected checks for any remaining usage of typing.Dict in the codebase # Test 1: Search for remaining imports of Dict from typing echo "Checking for remaining imports of Dict from typing:" rg --type py 'from typing import .*Dict' # Test 2: Search for remaining usage of typing.Dict echo "Checking for remaining usage of typing.Dict:" rg --type py 'typing\.Dict' # Test 3: Verify that dict is being used for type hinting echo "Verifying usage of dict for type hinting:" rg --type py '\bdict\['Length of output: 11096
package/PartSeg/_launcher/check_version.py (2)
43-45: Excellent refactoring of theIGNORE_FILEhandling!The changes improve the code in several ways:
- The use of a single
withstatement with multiple contexts makes the code more concise and readable.- Combining the file opening and
ValueErrorsuppression in one context manager is more Pythonic.- This approach leverages the multiple context feature available in Python 3.9+, which aligns well with the PR objective of dropping Python 3.8 support.
The functionality remains the same while enhancing code quality. Great job!
Line range hint
1-93: Summary of the reviewThe changes made to
check_version.pyare positive and align well with the PR objectives:
- The refactoring of the
IGNORE_FILEhandling improves code readability and leverages Python 3.9+ features, supporting the goal of dropping Python 3.8 support.- The overall structure and functionality of the
CheckVersionThreadclass remain sound.- Suggestions for enhancing error handling and user feedback have been provided, which could further improve the robustness of the version checking process.
Overall, the modifications contribute to better code quality while maintaining the existing functionality. Great work on this update!
package/PartSegCore/roi_info.py (3)
23-23: LGTM: Type hint update aligns with modern Python syntax.The change from
List[slice]tolist[slice]is in line with PEP 585 and the PR's objective to use Python 3.9+ syntax. This update improves readability without affecting the method's functionality.
48-49: LGTM: Consistent type hint updates for method parameters.The changes from
Dict[int, Any]todict[int, Any]andDict[str, np.ndarray]todict[str, np.ndarray]are in line with PEP 585 and the PR's objective. These updates improve readability and consistency without affecting the method's functionality.
Line range hint
1-108: Overall assessment: Changes successfully modernize type hints.The modifications in this file effectively update the type hints to use Python 3.9+ syntax, aligning with the PR objectives. These changes enhance code readability and consistency without altering the functionality. The only suggestion is to update the docstring in the
calc_boundsmethod to reflect the new type hint syntax.Great job on modernizing the type annotations in this file!
package/PartSeg/common_gui/stack_image_view.py (1)
2-2: Consider removing unused import.The
Uniontype is imported fromtypingbut is only used once in the visible part of the file. If it's not used elsewhere in the file, consider removing this import to keep the codebase clean.To verify if
Unionis used elsewhere in the file, you can run the following command:If this command only returns the line we've already reviewed, you can safely remove the import.
package/PartSegCore/image_operations.py (1)
1-1: Excellent update to the import statement.The change from
typing.Iterabletocollections.abc.Iterablealigns with modern Python practices (Python 3.9+). This update improves runtime checking capabilities for theIterableabstract base class.package/PartSegCore/project_info.py (5)
3-3: LGTM: Import statement updated correctly.The removal of
DictandListfrom thetypingimport is consistent with the PR objective to update type annotations to use Python 3.9+ syntax. The remaining imports are correctly maintained.
35-36: LGTM: Type annotations updated correctly.The type annotations for
roi_extraction_parametersandannotationshave been properly updated to use the built-indicttype instead ofDictfrom thetypingmodule. This change aligns with the PR objective and is correct for Python 3.9+.
68-68: LGTM: Return type annotation updated correctly.The return type annotation for the
get_roi_info_and_maskmethod has been properly updated to use the built-intupletype instead ofTuplefrom thetypingmodule. This change is consistent with the PR objective and is correct for Python 3.9+.
95-95: LGTM: Type annotation for class variable updated correctly.The type annotation for the
additional_layersclass variable has been properly updated to use the built-indicttype instead ofDictfrom thetypingmodule. This change aligns with the PR objective and is correct for Python 3.9+.
97-97: LGTM: Type annotation for class variable updated correctly.The type annotation for the
historyclass variable has been properly updated to use the built-inlisttype instead ofListfrom thetypingmodule. This change is in line with the PR objective and is correct for Python 3.9+.package/PartSeg/_roi_mask/batch_proceed.py (2)
22-22: Approved: Updated type hint to use Python 3.9+ syntaxThe change from
Tupletotuplein the type hint is a positive update. This modification aligns with Python 3.9+ type hinting syntax, improving code readability and consistency with modern Python practices. The change doesn't affect the runtime behavior of the code.
43-43: Approved: Updated type hint to use Python 3.9+ syntaxThe change from
Listtolistin the type hint is a positive update. This modification aligns with Python 3.9+ type hinting syntax, improving code readability and consistency with modern Python practices. The change doesn't affect the runtime behavior of the code, and the method implementation correctly handles both singleBatchTaskand list ofBatchTaskobjects.package/PartSegCore/napari_plugins/loader.py (4)
18-18: LGTM: Updated type annotation aligns with modern Python practices.The change from
typing.List[int]tolist[int]is a positive update that leverages Python 3.9+ type hinting syntax. This modification enhances code readability and aligns with the PR's objective of modernizing type annotations.
21-21: LGTM: Consistent type annotation update in main function signature.The change from
typing.List[int]tolist[int]within theUniontype is consistent with the earlier overload modification. This update maintains the function's flexibility while adopting modern type hinting syntax.
Line range hint
1-152: Summary: Type annotation updates align with PR objectives and modern Python practices.The changes in this file successfully update type annotations to use Python 3.9+ syntax, replacing
typing.Listwithlistandtyping.Typewithtype. These modifications enhance code readability and maintainability without affecting the runtime behavior. The changes are consistent throughout the file and align well with the PR's objective of modernizing the codebase and dropping support for Python 3.8.
138-138: LGTM: Updated type annotation for class type aligns with modern Python practices.The change from
typing.Type[LoadBase]totype[LoadBase]is a positive update that leverages Python 3.9+ type hinting syntax for class types. This modification enhances code readability and aligns with the PR's objective of modernizing type annotations.To ensure consistency across the codebase, let's verify the usage of
LoadBase:✅ Verification successful
Verified: All type annotations for
LoadBasehave been successfully updated totype[LoadBase]across the codebase.The absence of
typing.Type[LoadBase]and the consistent usage oftype[LoadBase]in multiple files confirm that the update aligns with modern Python practices. Additionally, the correct implementation in subclasses ofLoadBaseensures overall consistency and correctness.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the usage of LoadBase across the codebase # Test 1: Check for any remaining usage of typing.Type[LoadBase] echo "Checking for any remaining usage of typing.Type[LoadBase]:" rg --type python "typing\.Type\[LoadBase\]" # Test 2: Check for the updated usage of type[LoadBase] echo "Checking for the updated usage of type[LoadBase]:" rg --type python "type\[LoadBase\]" # Test 3: Check for any other usages or subclasses of LoadBase echo "Checking for other usages or subclasses of LoadBase:" rg --type python "class.*\(.*LoadBase.*\):"Length of output: 573
Script:
#!/bin/bash # Description: Verify the usage of LoadBase across the codebase # Test 1: Check for any remaining usage of typing.Type[LoadBase] echo "Checking for any remaining usage of typing.Type[LoadBase]:" rg "typing\.Type\[LoadBase\]" --glob "*.py" # Test 2: Check for the updated usage of type[LoadBase] echo "Checking for the updated usage of type[LoadBase]:" rg "type\[LoadBase\]" --glob "*.py" # Test 3: Check for any other usages or subclasses of LoadBase echo "Checking for other usages or subclasses of LoadBase:" rg "class\s+\w+\s*\(.*LoadBase.*\):" --glob "*.py"Length of output: 2518
package/PartSeg/_launcher/main_window.py (1)
37-37: Approved: Type hint modernizationThe change from
Type[BaseMainWindow]totype[BaseMainWindow]is a positive update. This modification:
- Aligns with PEP 585, which allows the use of built-in types as generic types.
- Reduces the need for importing from the
typingmodule.- Improves code readability.
- Is consistent with the PR objective of updating type annotations to use Python 3.9+ syntax.
This change doesn't affect the runtime behavior of the code and is a step towards more modern Python practices.
package/PartSegCore/register.py (1)
Line range hint
1-115: Consider additional improvements for consistency and clarity.While the main change is approved, here are some suggestions to further improve the file:
Update type hints in comments to use the new style consistently. For example, replace
Dictwithdict.Add type hints to important dictionaries like
register_dictandbase_class_dict. This will improve type checking and code readability.Investigate the areas marked with
# noinspection DuplicatedCode. There might be an opportunity to refactor and reduce code duplication.Here's an example of how you could add type hints to the dictionaries:
from typing import Dict, Type register_dict: Dict[RegisterEnum, Dict[str, Type[AlgorithmDescribeBase]]] = { RegisterEnum.flow: watershed.WatershedSelection.__register__, # ... (rest of the dictionary) } base_class_dict: Dict[RegisterEnum, Type[AlgorithmDescribeBase]] = { RegisterEnum.sprawl: watershed.BaseWatershed, # ... (rest of the dictionary) }To identify areas for type hint updates and potential code duplication, run:
#!/bin/bash echo "Checking for old-style type hints:" rg --type python 'Dict|List|Tuple|Set|FrozenSet|Type' package/PartSegCore/register.py echo "\nChecking for potential code duplication:" rg --type python '# noinspection DuplicatedCode' package/PartSegCore/register.pyAlso applies to: 116-130
package/PartSeg/common_gui/custom_load_dialog.py (7)
14-16: LGTM: Type annotations updated to modern Python syntaxThe changes to
LoadPropertyclass improve readability by using Python 3.9+ type hinting syntax. This update aligns with the PR objectives and modern Python practices.
19-19: LGTM: IORegister type alias updated to use built-in typesThe
IORegistertype alias has been successfully updated to use built-indictandlisttypes instead oftyping.Dictandtyping.List. This change improves readability and aligns with modern Python type hinting practices.
86-86: LGTM: Type annotation updated in CustomLoadDialogThe type annotation for the
historyparameter in theCustomLoadDialogclass has been updated to use the built-inlisttype. This change improves code readability and consistency with modern Python type hinting practices.
119-119: LGTM: Type annotation updated in get_result methodThe type annotation for
chosen_classin theget_resultmethod ofCustomLoadDialoghas been updated to usetype[LoadBase]. This change improves code consistency and aligns with modern Python type hinting practices.
126-126: LGTM: Type annotation updated in PLoadDialogThe type annotation for the
load_registerparameter in thePLoadDialogclass has been updated to use the built-indicttype. This change enhances code readability and maintains consistency with modern Python type hinting practices.
165-165: LGTM: Type annotation updated in SelectDirectoryDialogThe type annotation for the
settings_pathparameter in theSelectDirectoryDialogclass has been updated to use the built-inlisttype. This change improves code consistency and aligns with modern Python type hinting practices.
Line range hint
1-193: Summary: Successful update of type annotationsThe changes in this file consistently update type annotations to use Python 3.9+ syntax, replacing
typing.Listandtyping.Dictwithlistanddictrespectively. These modifications align perfectly with the PR objectives of dropping Python 3.8 support and adopting modern Python practices. The updates improve code readability and maintainability without altering any functionality.Key points:
- All changes are type annotation updates.
- Consistency is maintained throughout the file.
- No functional changes were introduced.
These updates contribute to a more modern and maintainable codebase.
azure-pipelines.yml (1)
Line range hint
1-235: Overall assessment: File changes align with PR objectivesThe update to Python 3.11 in the
GetTestDatastage is the only change in this file, which aligns well with the PR's objective of dropping support for older Python versions. The rest of the pipeline configuration remains unchanged, maintaining the existing workflow structure.To ensure the change doesn't introduce any unforeseen issues:
- Verify that all stages dependent on
GetTestDataare compatible with the artifacts produced by Python 3.11.- Run the entire pipeline to confirm that all stages complete successfully with this change.
- If any issues arise, consider updating other stages to use Python 3.11 for consistency, or investigate potential compatibility problems between different Python versions used across stages.
package/PartSeg/common_gui/custom_save_dialog.py (3)
18-18: LGTM: Updated type annotation to use Python 3.9+ syntaxThe change from
typing.List[str]tolist[str]in thesave_destinationtype annotation is correct and aligns with the PR objective of updating to modern Python syntax. This simplification improves readability without altering the underlying type information.
26-26: LGTM: Updated return type annotation to use Python 3.9+ syntaxThe change from
typing.Type[FormWidget]totype[FormWidget]in thewidget_classmethod's return type annotation is correct. This update simplifies the syntax while maintaining the same type information, in line with the PR's goal of modernizing type hints.
Line range hint
1-214: Summary: Successful update of type annotationsThe changes in this file consistently update type annotations to use Python 3.9+ syntax, improving code readability without altering functionality. These updates align well with the PR's objective of modernizing the codebase and dropping support for Python 3.8.
Key points:
typing.Listhas been replaced withlist.typing.Typehas been replaced withtype.- The changes maintain type safety while simplifying the syntax.
These updates contribute to a more modern and maintainable codebase.
.github/workflows/tests.yml (5)
53-53: LGTM: Python version matrix updated correctly.The Python version matrix has been updated to remove 3.8 and now includes versions 3.9 to 3.12. This change aligns with the PR objective to drop support for Python 3.8 and ensures testing on currently supported Python versions.
93-93: LGTM: Python version matrix updated consistently.The Python version matrix for the
base-test-mainjob has been updated to remove 3.8 and now includes versions 3.9 to 3.12. This change is consistent with the updates made in thebase-testjob and ensures that the main branch is tested with the same Python versions as the PR branches.
127-128: LGTM: Test coverage job updated to use Python 3.12.The
test_coveragejob has been updated to use Python 3.12 and the corresponding tox environment. This change ensures that code coverage is tested with the latest supported Python version, which is consistent with dropping Python 3.8 support and aligns with the PR objectives.
Line range hint
1-256: Overall assessment: Changes are consistent and align with PR objectives.The updates to
.github/workflows/tests.ymlconsistently remove Python 3.8 support and update the testing matrix to focus on Python versions 3.9 through 3.12. These changes align well with the PR objective of dropping Python 3.8 support. The workflow now ensures that all tests, including coverage, minimal configuration, and conda-based tests, are performed on supported Python versions.A few minor suggestions have been made to improve documentation and verify consistency across the project. These include adding comments to explain version choices and exclusions, and verifying the minimum supported Python version in the project configuration.
137-138: LGTM: Test minimal job updated to use Python 3.9.The
test_minimaljob has been updated to use Python 3.9 and the corresponding tox environment. This change is consistent with dropping Python 3.8 support and aligns with the PR objectives.Consider if testing the minimal configuration with the lowest supported Python version (3.9) is sufficient, or if it would be beneficial to also test with the latest supported version (3.12). Run the following script to check the project's stated Python version support:
✅ Verification successful
Verified: Project supports Python 3.9 as the minimum version.
The
test_minimaljob has been correctly updated to use Python 3.9, aligning with the project's supported Python versions.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check the project's stated Python version support # Expected result: Confirm that 3.9 is the minimum supported version grep -n "python_requires" pyproject.tomlLength of output: 74
Script:
#!/bin/bash # Description: Verify the project's minimum supported Python version in pyproject.toml # Expected result: Display the python_requires specification grep -n "python_requires" pyproject.tomlLength of output: 40
Script:
#!/bin/bash # Description: Search for Python version specifications in the codebase # Expected result: List all occurrences of Python version requirements rg -i "python_requires|python_version|python=" .Length of output: 1266
Script:
#!/bin/bash # Description: Search for Python version specifications below 3.9 in the codebase # Expected result: Identify if any Python versions below 3.9 are supported or excluded rg -i "python_version\s*<\s*'3\.[0-8]'" .Length of output: 49
package/PartSeg/_roi_analysis/partseg_settings.py (5)
Line range hint
34-39: LGTM: Type hint update forsave_locations_keysThe change from
typing.ClassVar[typing.List[str]]totyping.ClassVar[list[str]]is correct and aligns with the PR objective of updating type annotations to use Python 3.9+ syntax. This change maintains the same functionality while using more modern Python type hinting.
Line range hint
135-142: LGTM: Return type hint update forget_save_listThe change from
typing.List[SaveSettingsDescription]tolist[SaveSettingsDescription]is correct and aligns with the PR objective of updating type annotations to use Python 3.9+ syntax. This change maintains the same functionality while using more modern Python type hinting.
150-152: LGTM: Return type hint update forroi_pipelinesThe change from
typing.Dict[str, SegmentationPipeline]todict[str, SegmentationPipeline]is correct and aligns with the PR objective of updating type annotations to use Python 3.9+ syntax. This change maintains the same functionality while using more modern Python type hinting.
Line range hint
163-169: LGTM: Return type hint updates forbatch_plansandmeasurement_profilesThe changes from
typing.Dict[str, CalculationPlan]todict[str, CalculationPlan]forbatch_plansand fromtyping.Dict[str, MeasurementProfile]todict[str, MeasurementProfile]formeasurement_profilesare correct and align with the PR objective of updating type annotations to use Python 3.9+ syntax. These changes maintain the same functionality while using more modern Python type hinting.
Line range hint
1-169: Overall assessment: Excellent updates to type hintsThe changes in this file consistently update type hints from
typing.Listandtyping.Dicttolistanddict, aligning perfectly with the PR objective of dropping Python 3.8 support and updating to modern Python syntax. These changes improve code readability and maintainability without altering functionality.Great job on maintaining backwards compatibility with deprecation warnings where necessary. Consider adding deprecation timelines to these warnings for better user guidance.
The changes are well-executed and contribute to the overall goal of modernizing the codebase.
package/PartSeg/plugins/napari_widgets/algorithm_widgets.py (1)
220-220: LGTM: Updated type annotation to modern Python syntax.The change from
Type[BaseModel]totype[BaseModel]is a good update that aligns with modern Python type hinting syntax (Python 3.9+). This modification enhances code readability and leverages the latest language features without affecting runtime behavior.This change is consistent with the PR objective of updating type annotations and dropping support for Python 3.8.
package/PartSeg/common_gui/napari_viewer_wrap.py (3)
2-2: LGTM: Type annotation updates align with PR objectives.The changes to import statements and type annotations are in line with the PR objectives of updating to Python 3.9+ syntax. Specifically:
- Removal of
Listimport fromtypingmodule.- Update of return type annotation in
get_colormapsmethod to uselistinstead ofList.These modifications improve code readability and leverage modern Python type hinting capabilities.
Also applies to: 49-49
Line range hint
212-231: LGTM: Viewer class remains consistent with PR objectives.The Viewer class initialization and methods remain unchanged, which is in line with the PR objectives. The focus on Python version compatibility and type annotations is maintained without introducing functional changes to this class.
Line range hint
1-231: Summary: Changes align well with PR objectives and improve code quality.The modifications in this file successfully:
- Update type annotations to use Python 3.9+ syntax.
- Enhance widget interactivity in the SynchronizeWidget class.
- Maintain consistency with PR objectives by not introducing functional changes to the Viewer class.
These changes improve code readability and maintainability while aligning with the goal of dropping Python 3.8 support.
To ensure compatibility across the codebase, please run the following verification script:
This script will help identify any remaining instances of Python 3.8 specific syntax or inconsistent type annotation usage across the codebase.
package/PartSeg/common_gui/mask_widget.py (3)
Line range hint
1-8: LGTM: Import changes align with modern Python practices.The removal of
Listfrom thetypingimport is consistent with the PR objective of updating type annotations to use Python 3.9+ syntax. This change follows modern Python practices of using built-in types for annotations when possible, which is a good improvement.
Line range hint
112-118: LGTM: Type annotation update is correct and consistent.The change in the return type annotation from
Union[int, List[int]]toUnion[int, list[int]]is correct and aligns with the PR objective of updating to Python 3.9+ syntax. This update maintains the correct typing while using the built-inlisttype, which is appropriate for Python 3.9 and later versions.
Line range hint
1-218: Overall assessment: Changes are appropriate and align with PR objectives.The modifications in this file successfully update the type annotations to use Python 3.9+ syntax, specifically replacing
Listwithlist. These changes are consistent with the PR objectives of dropping Python 3.8 support and updating type annotations. The existing functionality appears to be maintained, and no new issues have been introduced. The code remains clean and readable after these updates.package/PartSegCore/segmentation/algorithm_base.py (2)
2-2: Excellent update to the import statement.The change from
collectionstocollections.abcfor importingMutableMappingis a recommended practice for Python 3.9+. This update improves future compatibility and follows best practices in Python development.
140-140: Consistent type annotation update.The change from
Dicttodictin the type annotation fornew_parametersis consistent with the earlier updates. This change aligns with modern Python type hinting practices and improves code readability.package/PartSegCore/analysis/batch_processing/parallel_backend.py (6)
28-28: LGTM: Correct import forAnyandCallableThe import of
AnyandCallablefrom thetypingmodule is correct and consistent with the PR objectives. These types are not available as built-in types in Python 3.9+, so they still need to be imported fromtyping.
71-71: LGTM: Updated return type hint to Python 3.9+ syntaxThe return type hint for the
get_resultmethod has been correctly updated to use the Python 3.9+ syntax. This change fromList[Tuple[uuid.UUID, Any]]tolist[tuple[uuid.UUID, Any]]aligns with the PR objectives and improves code readability.
87-87: LGTM: Updated parameter type hint to Python 3.9+ syntaxThe parameter type hint for
individual_parameters_listin theadd_workmethod has been correctly updated to use the Python 3.9+ syntax. This change fromListtolistaligns with the PR objectives and improves code consistency.
210-210: LGTM: Updated parameter type hint to Python 3.9+ syntaxThe parameter type hint for
calculation_dictin the__init__method ofBatchWorkerclass has been correctly updated to use the Python 3.9+ syntax. This change fromDict[uuid.UUID, Tuple[Any, Callable[[Any, Any], Any]]]todict[uuid.UUID, tuple[Any, Callable[[Any, Any], Any]]]aligns with the PR objectives and improves code readability.
218-218: LGTM: Updated parameter type hints to Python 3.9+ syntaxThe parameter type hints have been correctly updated to use the Python 3.9+ syntax in the following locations:
calculate_taskmethod:valparameter updated fromTuple[Any, uuid.UUID]totuple[Any, uuid.UUID].spawn_workerfunction:calculation_dictparameter updated fromDict[uuid.UUID, Any]todict[uuid.UUID, Any].These changes align with the PR objectives and improve code consistency.
Also applies to: 262-262
Line range hint
1-282: Summary: Successfully updated type hints to Python 3.9+ syntaxThis file has been successfully updated to use Python 3.9+ type hint syntax. The changes include:
- Replacing
Listwithlist- Replacing
Tuplewithtuple- Replacing
DictwithdictThese updates improve code readability and consistency while maintaining the original functionality. The changes align well with the PR objectives and modern Python practices. No potential issues or bugs were introduced by these modifications.
package/PartSeg/common_gui/advanced_tabs.py (1)
203-203: LGTM: Updated type annotation to modern Python syntax.The change from
List[str]tolist[str]for theimage_view_namesparameter aligns with Python 3.9+ type hinting syntax. This update improves code readability and leverages the latest Python features for type annotations.package/PartSeg/common_gui/label_create.py (6)
7-7: LGTM: Import changes align with modern Python practices.The changes to the import statements are appropriate:
- Importing
Sequencefromcollections.abcis the recommended approach.- Removing
Listfromtypingis consistent with using built-inlistfor type hinting in Python 3.9+.These modifications improve code readability and follow current best practices.
Also applies to: 11-11
79-79: LGTM: Type hint update inLabelShow.__init__The change from
List[Sequence[float]]tolist[Sequence[float]]for thelabelparameter is correct and consistent with Python 3.9+ type hinting practices. This update maintains the same semantic meaning while using the built-inlisttype.
184-184: LGTM: Type hint update inLabelChoose._label_showThe change from
List[Sequence[float]]tolist[Sequence[float]]for thelabelparameter in the_label_showmethod is correct and consistent with the previous updates. This modification aligns with Python 3.9+ type hinting practices while maintaining the same semantic meaning.
292-292: LGTM: Return type hint update inLabelEditor.get_colorsThe change from
List[List[int]]tolist[list[int]]for the return type of theget_colorsmethod is correct and consistent with the previous updates. This modification aligns with Python 3.9+ type hinting practices while maintaining the same semantic meaning.
333-333: LGTM: Type hint updates inLabelsLoad.loadThe changes in the
loadmethod of theLabelsLoadclass are correct and consistent:
- Parameter
load_locations:List[Union[str, BytesIO, Path]]→list[Union[str, BytesIO, Path]]- Return type:
List[List[float]]→list[list[float]]These modifications align with Python 3.9+ type hinting practices while maintaining the same semantic meanings.
Also applies to: 337-337
Line range hint
1-371: Overall assessment: Consistent type hint updates throughout the fileThe changes in this file are focused on updating type hints to use built-in types (e.g.,
listinstead ofList) in accordance with Python 3.9+ practices. These modifications have been applied consistently throughout the file, including:
- Import statements
- Method parameters
- Return type annotations
These updates improve code readability and align the codebase with modern Python standards without altering the functionality of the code. The changes are appropriate and well-executed.
package/PartSeg/_roi_analysis/profile_export.py (1)
156-159: LGTM! Type hints updated to use Python 3.9+ syntax.The changes to the type hints in the
ImportDialogconstructor are correct and align with the PR objectives. They improve readability by using built-in types (dictandtype) instead of theirtypingmodule equivalents. This update is consistent with Python 3.9+ type hinting syntax.Key improvements:
Dict→dictType→type- Retained
typing.Optionalfor non-container typesThese changes contribute to more modern and cleaner type annotations.
package/PartSeg/common_gui/universal_gui_part.py (3)
123-123: LGTM: Type annotation update aligns with PR objectives.The change from
typing.Tuple[float, float]totuple[float, float]for thedata_rangeparameter type annotation is correct. This update aligns with the PR objective of utilizing Python 3.9+ syntax for type annotations, which allows for more concise and readable code.
284-284: LGTM: Type annotation update consistent with PR goals.The modification of the
text_listparameter type annotation fromtyping.List[str]tolist[str]is appropriate. This change is in line with the PR's objective to update type annotations to Python 3.9+ syntax, promoting more concise and readable code.
Line range hint
1-384: Verify deprecation warning for EnumComboBox class.The AI-generated summary mentions a deprecation warning for the
EnumComboBoxclass, suggesting the use ofsuperqt.QEnumComboBoxinstead. However, this change is not visible in the provided diff. Please ensure that the deprecation warning has been correctly implemented.To verify the implementation of the deprecation warning, please run the following script:
package/PartSegCore/analysis/save_functions.py (2)
38-38: LGTM: Updated type hint for Python 3.9+ compatibility.The change from
typing.List[HistoryElement]tolist[HistoryElement]is consistent with the PR objective of dropping Python 3.8 support. This update improves readability by using the built-inlisttype.As mentioned in a previous review comment, please ensure that similar changes have been made consistently across the codebase, particularly in the files mentioned earlier:
package/PartSegCore/mask_create.pypackage/PartSeg/_roi_mask/stack_settings.pypackage/PartSegCore/analysis/calculation_plan.pypackage/PartSegCore/mask/io_functions.py
Line range hint
1-437: Overall assessment: Changes align with PR objectives.The modifications in this file successfully update type hints to use Python 3.9+ syntax, which is in line with the PR's goal of dropping Python 3.8 support. The changes improve code readability and modernize the type hinting approach.
To further enhance the codebase:
- Ensure similar updates are applied consistently across all files.
- Consider adopting Python 3.10+ type hinting features, such as the
|operator for union types, if the project's minimum Python version allows it.package/PartSeg/_roi_mask/stack_settings.py (5)
Line range hint
25-32: LGTM: Updated type annotation to use native Python syntax.The change from
typing.List[str]tolist[str]forsave_locations_keysaligns with Python 3.9+ type hinting syntax. This update improves code readability and consistency with modern Python practices without affecting functionality.
39-39: LGTM: Updated type annotation to use native Python syntax.The change from
typing.Dict[int, ROIExtractionProfile]todict[int, ROIExtractionProfile]forcomponents_parameters_dictaligns with Python 3.9+ type hinting syntax. This update improves code readability and consistency with modern Python practices without affecting functionality.
Line range hint
89-101: LGTM: Updated return type annotation to use native Python syntax.The change from
typing.List[int]tolist[int]for the return type ofchosen_componentsmethod aligns with Python 3.9+ type hinting syntax. This update improves code readability and consistency with modern Python practices without affecting functionality.
Line range hint
283-289: LGTM: Updated parameter type annotation to use native Python syntax.The change from
typing.List[HistoryElement]tolist[HistoryElement]for thehistoryparameter in thecompare_historymethod aligns with Python 3.9+ type hinting syntax. This update improves code readability and consistency with modern Python practices without affecting functionality.
Line range hint
1-341: Summary: Successful transition to Python 3.9+ type hinting syntaxThis file has been successfully updated to use Python 3.9+ type hinting syntax, replacing
typing.Listandtyping.Dictwithlistanddictrespectively. These changes improve code readability and maintainability while preparing the codebase for newer Python versions. The updates are consistent throughout the file and align with the PR objective of dropping Python 3.8 support.Key points:
- All type annotations have been updated without affecting functionality.
- The changes are consistent across class variables, instance variables, method parameters, and return types.
- Most docstrings have been updated to reflect the new syntax, with a couple of minor suggestions for improvement.
These updates contribute to a more modern and maintainable codebase.
package/PartSegCore/analysis/measurement_base.py (9)
3-3: LGTM: Improved import for IterableThe change from
typing.Iterabletocollections.abc.Iterableis a good practice. It aligns with modern Python conventions and prepares the code for future Python versions.
60-60: LGTM: Updated type annotation for has_mask_componentsThe type annotation change from
Tupletotuplealigns with Python 3.9+ type hinting syntax. The function's logic remains intact, and this update improves code consistency with modern Python practices.
68-68: LGTM: Updated type annotation for has_roi_componentsThe type annotation change from
Tupletotupleis consistent with the previous function and aligns with Python 3.9+ type hinting syntax. This update maintains code consistency and readability.
128-128: LGTM: Updated type annotations in Leaf class methodsThe type annotation changes in the
Leafclass methods (get_channel_num,_parameters_string,_plugin_info, andpretty_print) consistently updateDicttodict. These changes align with Python 3.9+ type hinting syntax and improve code consistency without altering the methods' logic.Also applies to: 157-157, 172-172, 185-185
272-272: LGTM: Updated type annotations in Node class methodsThe type annotation changes in the
Nodeclass methods (get_channel_numandpretty_print) are consistent with the updates made in theLeafclass. These changes align with Python 3.9+ type hinting syntax and maintain code consistency across the file.Also applies to: 282-282
328-328: LGTM: Updated type annotation in MeasurementEntry classThe type annotation change in the
MeasurementEntryclass'sget_channel_nummethod is consistent with the updates made in other classes. This change maintains code consistency and aligns with Python 3.9+ type hinting syntax.
343-343: LGTM: Updated type annotation in MeasurementMethodBase classThe type annotation change for the
need_class_methodclass variable fromList[str]tolist[str]is consistent with the other updates in the file. This change aligns with Python 3.9+ type hinting syntax and improves code consistency.
375-376: LGTM: Updated type annotations in calculate_property methodThe type annotation changes in the
calculate_propertystatic method forroi_alternativeandroi_annotationparameters are consistent with the other updates in the file. These changes align with Python 3.9+ type hinting syntax and improve code consistency without altering the method's functionality.
Line range hint
1-424: Summary: Consistent type annotation updates across the fileThe changes in this file focus on updating type annotations to use built-in types (e.g.,
list,dict,tuple) instead of their counterparts from thetypingmodule. These updates are consistent throughout the file and align with Python 3.9+ type hinting syntax. The changes improve code consistency and prepare the codebase for future Python versions while maintaining backwards compatibility. No functional changes or logic alterations were made, ensuring that the existing behavior remains intact.package/PartSegCore/analysis/load_functions.py (8)
Line range hint
168-173: LGTM: Type hint update for Python 3.9+ compatibilityThe change from
typing.Listtolistfor theload_locationsparameter is correct and aligns with the PR objective to update type annotations for Python 3.9+ compatibility. This modification doesn't affect the functionality of the method.
Line range hint
188-193: LGTM: Type hint update for Python 3.9+ compatibilityThe change from
typing.Listtolistfor theload_locationsparameter is correct and aligns with the PR objective to update type annotations for Python 3.9+ compatibility. This modification doesn't affect the functionality of the method.
Line range hint
227-232: LGTM: Type hint update for Python 3.9+ compatibilityThe change from
typing.Listtolistfor theload_locationsparameter is correct and aligns with the PR objective to update type annotations for Python 3.9+ compatibility. This modification doesn't affect the functionality of the method.
249-249: LGTM: Type hint update for Python 3.9+ compatibilityThe change from
typing.Listtolistfor thefile_pathsparameter is correct and aligns with the PR objective to update type annotations for Python 3.9+ compatibility. This modification doesn't affect the functionality of the method.
Line range hint
266-271: LGTM: Type hint update for Python 3.9+ compatibilityThe change from
typing.Listtolistfor theload_locationsparameter is correct and aligns with the PR objective to update type annotations for Python 3.9+ compatibility. This modification doesn't affect the functionality of the method.
Line range hint
300-305: LGTM: Type hint update for Python 3.9+ compatibilityThe change from
typing.Listtolistfor theload_locationsparameter is correct and aligns with the PR objective to update type annotations for Python 3.9+ compatibility. This modification doesn't affect the functionality of the function.
352-356: LGTM: Type hint updates for Python 3.9+ compatibilityThe changes from
typing.Listtolistfor theload_locationsparameter in theloadmethods ofLoadMaskSegmentation,LoadProfileFromJSON, andLoadImageForBatchclasses are correct and align with the PR objective to update type annotations for Python 3.9+ compatibility.Additionally, the return type hints have been updated:
LoadMaskSegmentation.load:list[ProjectTuple]LoadProfileFromJSON.load:tuple[dict, list]These modifications don't affect the functionality of the methods and correctly use the new syntax for type hints in Python 3.9+.
Also applies to: 378-382, 430-434
Line range hint
1-464: Summary: Successful type hint updates for Python 3.9+ compatibilityThe changes in this file consistently update type hints from
typing.Listtolistfor various method parameters, primarilyload_locations. Additionally, some return type hints have been updated to use the new syntax (e.g.,list[ProjectTuple],tuple[dict, list]).These modifications align with the PR objective to update type annotations for Python 3.9+ compatibility. No functional changes or issues were identified during the review.
The updates improve code readability and maintain consistency with modern Python typing practices.
package/PartSegCore/io_utils.py (9)
66-66: LGTM: Type hint update forget_extensionsThe return type hint has been updated from
typing.List[str]tolist[str], which is consistent with modern Python practices (Python 3.9+). This change improves readability without affecting the method's functionality.
77-77: LGTM: Type hint update forneed_functionsThe type hint for the
need_functionsclass variable has been updated fromtyping.ClassVar[typing.List[str]]totyping.ClassVar[list[str]]. This change aligns with modern Python type hinting practices while maintaining the variable's functionality.
126-126: LGTM: Type hint update forneed_functionsThe type hint for the
need_functionsclass variable in theLoadBaseclass has been updated fromtyping.ClassVar[typing.List[str]]totyping.ClassVar[list[str]]. This change is consistent with the previous update in theSaveBaseclass and aligns with modern Python type hinting practices.
144-148: LGTM: Type hint updates inloadmethodThe
loadmethod signature has been updated with modern type hints:
load_locationsparameter:typing.List[...]→list[...]- Return type:
typing.List[ProjectInfoBase]→list[ProjectInfoBase]These changes improve readability and are consistent with Python 3.9+ type hinting practices.
170-170: LGTM: Type hint update inget_next_filemethodThe
file_pathsparameter type hint in theget_next_filemethod has been updated fromtyping.List[str]tolist[str]. This change is consistent with the previous updates and aligns with modern Python type hinting practices.
221-221: LGTM: Type hint update infind_problematic_entriesfunctionThe return type hint has been updated from
typing.List[typing.MutableMapping]tolist[typing.MutableMapping]. This change is consistent with the previous updates and aligns with modern Python type hinting practices.
239-239: LGTM: Type hint update infind_problematic_leafsfunctionThe return type hint has been updated from
typing.List[typing.MutableMapping]tolist[typing.MutableMapping]. This change is consistent with the previous updates and aligns with modern Python type hinting practices.
274-274: LGTM: Type hint update inopen_tar_filefunctionThe return type hint has been updated from
typing.Tuple[TarFile, str]totuple[TarFile, str]. This change is consistent with the previous updates and aligns with modern Python type hinting practices.
Line range hint
1-524: Summary: Consistent type hint updates across the fileThis review covered the changes made to
package/PartSegCore/io_utils.py. The primary modifications involve updating type hints fromtyping.Listandtyping.Tupletolistandtuple, respectively. These changes align with modern Python practices (Python 3.9+) and improve code readability.Key points:
- All changes are consistent throughout the file.
- No functional changes were made; only type hints were updated.
- The updates do not introduce any new issues or affect existing functionality.
One minor suggestion:
- Consider addressing the TODO comment in the
load_metadata_partfunction to improve code organization.Overall, these changes represent a positive step towards modernizing the codebase and improving its maintainability.
package/PartSeg/plugins/napari_widgets/roi_extraction_algorithms.py (5)
67-68: LGTM: Updated type hint to use built-inlistThe change from
typing.List[str]tolist[str]aligns with PEP 585 and improves code readability. This update is correct and follows modern Python type hinting conventions.
70-72: LGTM: Updated type hint to use built-indictThe change from
typing.Dict[str, Layer]todict[str, Layer]is consistent with the previous update and aligns with PEP 585. This improvement enhances code readability and follows modern Python type hinting conventions.
157-158: LGTM: Updated type hint to use built-indictThe change from
typing.Dict[str, ROIExtractionProfile]todict[str, ROIExtractionProfile]is consistent with the previous updates. This change aligns with PEP 585, enhances code readability, and follows modern Python type hinting conventions.
300-303: LGTM: Updated type hints to use built-in typesThe changes to the type hints in the
__init__method ofProfilePreviewDialogare consistent with the previous updates:
profile_dict: dict[str, ROIExtractionProfile]algorithm_selection: type[AlgorithmSelection]These updates align with PEP 585, enhance code readability, and follow modern Python type hinting conventions.
Line range hint
1-424: Summary: Consistent type hint updates improve code qualityThe changes in this file are part of a larger effort to modernize the codebase and drop support for Python 3.8. All modifications involve updating type hints to use built-in types (e.g.,
list,dict,type) instead of their counterparts from thetypingmodule. These changes:
- Align with PEP 585, which allows for the use of built-in collection types as generic types.
- Improve code readability and maintainability.
- Follow modern Python type hinting conventions.
The updates are consistent throughout the file and do not introduce any logical changes or bug fixes. This modernization effort enhances the overall code quality and prepares the codebase for newer Python versions.
package/PartSeg/common_gui/multiple_file_widget.py (2)
106-107: Excellent update to modern type hinting!The change from
List[Tuple[List[str], str]]tolist[tuple[list[str], str]]aligns with PEP 585, which allows the use of built-in collection types in annotations. This update improves readability and leverages the latest Python type hinting capabilities.
Line range hint
1-376: Overall excellent update to modern type hinting!The changes in this file consistently update type hints to use the modern Python 3.9+ syntax, aligning with PEP 585. This improves code readability and leverages the latest Python type hinting capabilities without altering the functionality of the code. Great job on maintaining consistency throughout the file!
A few minor suggestions have been made for further improvements, but overall, this is a solid update that enhances the code quality.
package/PartSegCore/utils.py (2)
271-271: LGTM: Updated type annotation improves readabilityThe change from
typing.Dict[str, typing.List[CallbackBase]]todict[str, list[CallbackBase]]reflects modern Python type hinting syntax (Python 3.9+). This update enhances code readability and aligns with the PR's objective of updating type annotations. Good job on keeping the codebase up-to-date with current Python practices.
Line range hint
1-524: Summary: Type annotation updates align with PR objectivesThe changes in this file successfully update type annotations to use Python 3.9+ syntax, which aligns with the PR's objective of dropping Python 3.8 support. These updates improve code readability and maintain consistency throughout the codebase. No functional changes or potential issues were introduced by these updates.
package/PartSeg/_roi_analysis/measurement_widget.py (4)
58-58: LGTM: Updated type annotation aligns with PR objectivesThe change from
List[MeasurementResult]tolist[MeasurementResult]is correct and aligns with the PR objective of updating type annotations to use Python 3.9+ syntax. This update maintains the same semantic meaning while using more modern syntax.
118-118: LGTM: Consistent type annotation updateThe change from
List[str]tolist[str]in the return type annotation is correct and consistent with the PR objective of updating type annotations to use Python 3.9+ syntax. This update maintains the same semantic meaning while using more modern syntax.
124-124: LGTM: Consistent type annotation updateThe change from
List[str]tolist[str]in the return type annotation is correct and consistent with the PR objective of updating type annotations to use Python 3.9+ syntax. This update maintains the same semantic meaning while using more modern syntax.
317-317: LGTM: Consistent type annotation updateThe change from
List[Tuple[QWidget, int]]tolist[tuple[QWidget, int]]in the parameter type annotation is correct and consistent with the PR objective of updating type annotations to use Python 3.9+ syntax. This update maintains the same semantic meaning while using more modern syntax.package/PartSeg/common_gui/main_window.py (5)
5-5: LGTM: Removed unused importThe removal of the
Listimport fromtypingis in line with the PR objective of updating to Python 3.9+ type hinting syntax. This change modernizes the code without affecting its functionality.
133-133: LGTM: Updated return type hintThe change from
Type[BaseSettings]totype[BaseSettings]aligns with the PR objective of updating to Python 3.9+ type hinting syntax. This modernization improves code readability without altering functionality.
164-164: LGTM: Updated type hint for viewer_listThe change from
List[Viewer]tolist[Viewer]forself.viewer_listis in line with the PR objective of updating to Python 3.9+ type hinting syntax. This update enhances code readability while maintaining the same functionality.
222-222: LGTM: Updated return type hint for get_colormapsThe change from
List[Optional[colormap.Colormap]]tolist[Optional[colormap.Colormap]]in theget_colormapsmethod signature aligns with the PR objective of updating to Python 3.9+ type hinting syntax. This update improves code consistency and readability without altering the method's functionality.
Line range hint
1-387: Overall assessment: Consistent and appropriate type hint updatesThe changes made to this file are consistent with the PR objective of updating type annotations to use Python 3.9+ syntax. All modifications involve replacing
typing.Listwith the built-inlisttype for type hinting. These updates improve code readability and align the codebase with modern Python practices without altering any functionality. The changes are applied consistently throughout the file, demonstrating a thorough approach to the modernization effort.package/PartSeg/common_gui/error_report.py (3)
261-263: Improved type hinting in ExceptionListItem.initThe type hint for the
exceptionparameter has been updated to use built-in typestupleandlistinstead oftyping.Tupleandtyping.List. This change simplifies the type annotation and is consistent with Python 3.9+ syntax.
302-305: Improved type hinting in DataImportErrorDialog.initThe type hint for the
errorsparameter has been updated to use built-in typesdict,list, andtupleinstead oftyping.Dict,typing.List, andtyping.Tuple. This change simplifies the type annotation and is consistent with Python 3.9+ syntax.
Line range hint
1-465: Summary of changes in error_report.pyThe changes in this file are focused on updating type hints to use Python 3.9+ syntax. Specifically:
- In
ExceptionListItem.__init__, theexceptionparameter type hint was updated.- In
DataImportErrorDialog.__init__, theerrorsparameter type hint was updated.These changes align with the PR objective of dropping Python 3.8 support and updating type annotations. They improve code readability and maintainability by using more modern Python syntax without altering the functionality of the code.
package/PartSeg/_roi_analysis/export_batch.py (2)
311-311: Improved type annotation using built-in typesThe return type annotation has been updated to use built-in types
listandtupleinstead oftyping.Listandtyping.Tuple. This change simplifies the type hint and is consistent with Python 3.9+ syntax, improving readability and reducing the need for importing from thetypingmodule.
Line range hint
424-435: Improved flexibility with newzenodo_urlparameterThe addition of the
zenodo_urlparameter with a default value allows for greater flexibility in specifying the Zenodo API URL. This change is beneficial for testing or using different Zenodo instances (e.g., sandbox environment) while maintaining backward compatibility.However, there are a couple of points to consider:
- The function's docstring should be updated to include information about the new
zenodo_urlparameter.- The
ExportProjectDialogclass might need to be updated to utilize this new parameter when calling theexport_to_zenodofunction.Consider updating the function's docstring to include the new
zenodo_urlparameter:def export_to_zenodo( excel_path: Path, base_folder: Path, zenodo_token: str, title: str, author: str, affiliation: str, orcid: str, description: str, zenodo_url: str = "https://zenodo.org/api/deposit/depositions", ): """ Export project to Zenodo :param excel_path: path to Excel file with output from batch processing :param base_folder: base folder from where paths are calculated :param zenodo_token: Zenodo API token :param title: title of the deposition :param author: author of the deposition :param affiliation: affiliation of the author :param orcid: ORCID of the author :param description: description of the deposition :param zenodo_url: Zenodo API URL (default: "https://zenodo.org/api/deposit/depositions") :return: deposit URL """Let's verify if the
ExportProjectDialogclass needs to be updated:package/PartSeg/common_gui/colormap_creator.py (9)
4-4: Update import statement for better compatibility.The import statement for
Iterablehas been updated to usecollections.abcinstead oftyping. This change improves compatibility with newer Python versions and follows best practices.
75-76: Type annotations updated for better readability.The type annotations for
color_listandposition_listhave been updated to use the built-inlisttype instead ofListfrom thetypingmodule. This change improves readability and aligns with modern Python type hinting practices.
491-491: Type annotations updated in method signature and attribute.The type annotations in the
__init__method ofColormapListclass and the_widget_dictattribute have been updated to use built-in types (dict,tuple,list) instead oftypingmodule types. This change improves readability and aligns with modern Python type hinting practices.Also applies to: 498-498
519-519: Return type annotations updated for better clarity.The return type annotations for
get_selectedandblockedmethods in theColormapListclass have been updated to use the built-insettype instead ofSetfrom thetypingmodule. This change improves readability and aligns with modern Python type hinting practices.Also applies to: 530-530
544-544: Type annotation updated for better readability.The type annotation for the
cache_dictvariable has been updated to use the built-indicttype instead ofDictfrom thetypingmodule. This change improves readability and aligns with modern Python type hinting practices.
620-620: Type annotations updated in method signatures.The type annotations in the
__init__,get_selected, andblockedmethods of thePColormapListclass have been updated to use built-in types (list,set) instead oftypingmodule types. This change improves readability and aligns with modern Python type hinting practices.Also applies to: 628-628, 635-635
688-688: Type annotation updated in method signature.The type annotation for the
load_locationsparameter in theloadmethod of theColormapLoadclass has been updated to use the built-inlisttype instead ofListfrom thetypingmodule. This change improves readability and aligns with modern Python type hinting practices.
Line range hint
1-700: Consider adding type checking to the CI pipeline.Given the extensive use of type annotations in this file, it would be beneficial to add a type checking step (e.g., using mypy) to the CI pipeline. This would help catch type-related issues early in the development process.
#!/bin/bash # Check if mypy is configured in the project fd mypy.ini fd .mypy.ini grep -r "mypy" .github/workflows
Line range hint
636-643: Improve error handling in theblockedmethod.The
blockedmethod in thePColormapListclass uses a TODO comment indicating that only currently presented channels should be checked. Additionally, the method doesn't handle potentialKeyErrorexceptions when accessing settings. Consider implementing proper error handling and resolving the TODO comment.package/PartSegImage/image_reader.py (7)
129-131: LGTM: Type annotation updatesThe type annotations for
channel_names,colors, andrangeshave been updated to use built-in types (list) instead oftyping.List. This change aligns with modern Python type hinting practices (Python 3.9+) and improves readability without altering functionality.
137-137: LGTM: Return type annotation updateThe return type annotation for the
_get_channel_infomethod has been updated fromtyping.List[ChannelInfo]tolist[ChannelInfo]. This change is consistent with modern Python type hinting practices and improves readability without altering functionality.
172-172: LGTM: Parameter type annotation updateThe type annotation for the
default_spacingparameter has been updated fromtyping.Optional[typing.Tuple[float, float, float]]totyping.Optional[tuple[float, float, float]]. This change aligns with modern Python type hinting practices and improves readability without altering functionality.
191-191: LGTM: Return type annotation updateThe return type annotation for the
_reduce_obsolete_dummy_axesmethod has been updated fromtyping.Tuple[np.ndarray, str]totuple[np.ndarray, str]. This change is consistent with modern Python type hinting practices and improves readability without altering functionality.
272-272: LGTM: Parameter type annotation updateThe type annotation for the
default_spacingparameter has been updated fromtyping.Optional[typing.Tuple[float, float, float]]totyping.Optional[tuple[float, float, float]]. This change aligns with modern Python type hinting practices and improves readability without altering functionality.
319-322: LGTM: Improved context manager readabilityThe context manager structure has been updated to use parentheses, improving code readability without altering functionality. This change is consistent with PEP 8 style guidelines for line breaks in
withstatements.
415-415: LGTM: Type annotation updates for_search_for_filesmethodThe type annotations for the
_search_for_filesmethod have been updated:
- The
channelsparameter type has changed fromtyping.List["Element"]tolist["Element"].- The return type has changed from
typing.List[Image]tolist[Image].These changes align with modern Python type hinting practices and improve readability without altering functionality.
Also applies to: 418-418
package/PartSeg/_roi_analysis/batch_window.py (2)
77-78: LGTM: Type hint update aligns with PR objectives.The change from
typing.Listtolistin the return type hint is consistent with the PR's goal of updating type annotations to use Python 3.9+ syntax. This modification enhances code readability and leverages modern Python features.
Line range hint
379-386: LGTM: Type hint update consistent with PR goals.The change from
typing.Listtolistin thefile_listparameter type hint is in line with the PR's objective of updating type annotations to use Python 3.9+ syntax. This modification improves code readability and utilizes modern Python features.package/PartSegCore/mask/io_functions.py (5)
72-73: LGTM! Type hint updates improve readability.The changes from
typing.Listtolistandtyping.Dicttodictare consistent with modern Python type hinting practices for Python 3.9+. This update improves code readability and aligns with the PR objectives.Also applies to: 75-75, 85-87, 90-90, 92-92
125-125: LGTM! Consistent type hint update.The change from
typing.List[float]tolist[float]for thespacingattribute is consistent with the other type hint updates in the file and improves code readability.
497-497: LGTM! Please clarify the return type change.The type hint updates are consistent with the other changes in the file. However, the return type of the
loadmethod has been changed totyping.Union[ProjectInfoBase, list[ProjectInfoBase]]. This is different from the return types of otherloadmethods in the file, which typically returnMaskProjectTuple.Could you please clarify why this method might return a list of
ProjectInfoBaseobjects? If this is intentional, consider adding a comment explaining the different possible return types to improve code clarity.Also applies to: 508-512, 575-575
717-717: LGTM! Consistent type hint update.The change from
typing.Listtolistin the return type hint of theget_fieldsmethod is consistent with the other type hint updates in the file and improves code readability.
733-737: LGTM! Please clarify the return type change.The type hint updates in the
loadmethod signature are consistent with the other changes in the file. However, the return type has been changed totyping.Union[ProjectInfoBase, list[ProjectInfoBase]]. This is different from the return types of otherloadmethods in the file, which typically returnMaskProjectTuple.Could you please clarify why this method might return a list of
ProjectInfoBaseobjects? If this is intentional, consider adding a comment explaining the different possible return types to improve code clarity. Also, ensure that this change is consistent with the actual implementation of the method.package/PartSegCore/analysis/calculation_plan.py (3)
301-301: LGTM: Type annotation update aligns with PR objectivesThe change from
typing.List["CalculationTree"]tolist["CalculationTree"]for thechildrenparameter type annotation is consistent with the PR's goal of updating to Python 3.9+ syntax. This improves readability while maintaining the same functionality.
407-407: LGTM: Type annotation update aligns with PR objectivesThe change from
typing.List[str]tolist[str]for thefile_listattribute type annotation is consistent with the PR's goal of updating to Python 3.9+ syntax. This improves readability while maintaining the same functionality.
552-552: LGTM: Type annotation update aligns with PR objectivesThe change from
typing.List[MeasurementCalculate]tolist[MeasurementCalculate]for the return type annotation is consistent with the PR's goal of updating to Python 3.9+ syntax. This improves readability while maintaining the same functionality.package/PartSeg/common_gui/channel_control.py (8)
33-33: Type annotation update: Improved readabilityThe type annotation for
ColorMapDicthas been updated to use the built-intupletype instead oftyping.Tuple. This change aligns with modern Python type hinting practices and improves code readability.
111-111: Type annotation update: Simplified list typeThe type annotation for the
colorsparameter in theColorComboBox.__init__method has been updated fromtyping.List[str]tolist[str]. This change simplifies the type hint and aligns with modern Python type hinting practices.
157-157: Type annotation update: Simplified list type in method signatureThe type annotation for the
colorsparameter in theColorComboBox.change_colorsmethod has been updated fromtyping.List[str]tolist[str]. This change is consistent with the previous updates and improves code readability.
302-302: Type annotation update: Simplified dictionary typeThe type annotation for
self.widget_dictin theChannelPropertyclass has been updated fromtyping.Dict[str, ColorComboBoxGroup]todict[str, ColorComboBoxGroup]. This change is consistent with the previous updates and improves code readability.
510-510: Type annotation update: Optional list typeThe type annotation for the
colorsparameter in theColorComboBoxGroup.update_color_listmethod has been updated to usetyping.Optional[list[str]]instead oftyping.Optional[typing.List[str]]. This change is consistent with the previous updates and improves code readability.
527-527: Type annotation updates: Simplified return typesThe return type annotations for several properties in the
ColorComboBoxGroupclass have been updated to uselistinstead oftyping.List. These changes are consistent with the previous updates and improve code readability:
selected_colormapschannel_visibilitycurrent_colorscurrent_colormapsAlso applies to: 536-536, 544-544, 556-556
618-618: Type annotation updates: Simplified return types for methodsThe return type annotations for several methods in the
ColorComboBoxGroupclass have been updated to uselistinstead oftyping.List. These changes are consistent with the previous updates and improve code readability:
get_filterget_limitsget_gammaAlso applies to: 627-628, 637-637
Line range hint
1-738: Summary: Consistent type annotation updates improve code qualityThe changes in this file focus on updating type annotations throughout the code. These updates include:
- Replacing
typing.Listwithlist- Replacing
typing.Dictwithdict- Replacing
typing.TuplewithtupleThese changes align the code with modern Python type hinting practices and improve overall readability. The consistent application of these updates throughout the file enhances code maintainability and prepares the codebase for compatibility with newer Python versions.
While these changes don't affect the functionality of the code, they represent a positive step towards a more standardized and future-proof codebase.
package/PartSeg/common_backend/base_settings.py (5)
9-13: LGTM! Good update to import statements.The changes to the import statements are beneficial:
- Adding
Sequencefromcollections.abcis more specific and preferred overtyping.Sequence.- Removing
List,Dict, andTuplefromtypingaligns with PEP 585, allowing the use of built-in types for annotations in Python 3.9+. This simplifies the code and makes it more future-proof.
97-98: LGTM! Consistent type annotation update.The change from
Dict[str, AdditionalLayerDescription]todict[str, AdditionalLayerDescription]in theadditional_layersmethod signature is consistent with the import changes and aligns with PEP 585. This update improves readability and simplifies the type annotation.
266-267: LGTM! Consistent type annotation update.The change from
Optional[Tuple[str, np.ndarray]]toOptional[tuple[str, np.ndarray]]in thecached_labelsproperty type annotation is consistent with the import changes and aligns with PEP 585. This update improves readability and simplifies the type annotation.
Line range hint
457-472: LGTM! Consistent type annotation updates throughout the class.The changes in the BaseSettings class are well-implemented and consistent:
- Class variable
save_locations_keysupdated toClassVar[list[str]].- Instance variable
historyupdated tolist[HistoryElement].- Method signatures updated to use
listinstead ofList:
_load_files_callset_historyget_historyget_save_listget_last_filesget_last_files_multipleThese updates align with PEP 585, improve readability, and simplify the type annotations consistently throughout the class.
Also applies to: 533-533, 567-571, 590-598, 618-618, 630-633
Line range hint
1-735: Great job updating type annotations throughout the file!The changes made to
package/PartSeg/common_backend/base_settings.pyare consistent and well-implemented:
- Import statements have been updated to remove unnecessary imports from
typing.- Type annotations throughout the file have been changed to use built-in types (e.g.,
list,dict,tuple) instead of theirtypingcounterparts.- These changes align with PEP 585 and make the code compatible with Python 3.9+.
- The updates improve code readability and make it more future-proof.
- No functional changes have been made to the code logic, reducing the risk of introducing new bugs.
The systematic approach to updating the codebase is commendable. These changes will make the code easier to maintain and more consistent with modern Python practices.
package/PartSeg/_roi_analysis/main_window.py (1)
536-537: LGTM! Type annotation updated to use newer Python syntax.The change from
Type[PartSettings]totype[PartSettings]in the return type annotation reflects an update to use newer Python type hinting syntax (Python 3.9+). This change improves consistency with modern Python practices without affecting the method's functionality.package/PartSeg/common_gui/algorithms_description.py (7)
Line range hint
285-291: LGTM: Improved type annotationsThe changes to the
get_getter_and_setter_functionmethod's return type annotation are well-implemented. They improve type specificity and readability while aligning with the goal of using more modern Python syntax. The function's behavior remains unchanged.
323-324: LGTM: Updated type annotationThe change to the
field_listparameter's type annotation in theFieldsListclass constructor is appropriate. It uses the more modern Python syntax for type hinting lists, which is consistent with the goal of dropping Python 3.8 support. This change improves code readability without altering the class's functionality.
381-382: LGTM: Updated type aliasThe changes to the
FieldAllowedTypestype alias are well-implemented. They use the more modern Python syntax for type hinting, which is consistent with the goal of dropping Python 3.8 support. These updates improve code readability and type specificity without altering the meaning of the type alias.
398-399: LGTM: Updated type annotationsThe changes to the type annotations in the
FormWidgetclass are appropriate. They use the more modern Python syntax for type hinting dictionaries and lists, which is consistent with the goal of dropping Python 3.8 support. These updates improve code readability and type specificity without altering the class's functionality.
511-511: LGTM: Updated type annotationsThe changes to the type annotations in the
SubAlgorithmWidgetclass are well-implemented. They use the more modern Python syntax for type hinting dictionaries, which is consistent with the goal of dropping Python 3.8 support. The return type annotation for theget_valuesmethod has been made more specific. These updates improve code readability and type specificity without altering the class's functionality.Also applies to: 562-564
614-614: LGTM: Updated type annotations across multiple classesThe changes to the type annotations in the
BaseAlgorithmSettingsWidget,InteractiveAlgorithmSettingsWidget, andAlgorithmChooseBaseclasses are well-implemented. They use the more modern Python syntax for type hinting, which is consistent with the goal of dropping Python 3.8 support. These updates improve code readability and type specificity without altering the functionality of the classes. The changes include:
- Updated
algorithmparameter type hints in__init__methods.- Updated
algorithm_dicttype annotation inAlgorithmChooseBase.These modifications contribute to a more consistent and modern codebase.
Also applies to: 720-721, 754-754, 756-756, 763-763, 855-856
Line range hint
285-856: Summary: Successful modernization of type annotationsThe changes made to this file successfully modernize the type annotations throughout the codebase. Key points:
- Consistent use of
list,dict, andtypeinstead of theirtypingmodule counterparts.- Updated return type annotations for improved specificity.
- These changes align with the goal of dropping Python 3.8 support and using more modern Python syntax.
- The updates improve code readability and maintainability without altering the functionality.
Overall, these changes contribute to a more consistent and up-to-date codebase, which will be easier to maintain and understand in the future.
package/PartSegImage/image.py (1)
17-18: LGTM! Type alias updates improve readability.The changes to
Spacingand_IMAGE_DATAtype aliases align with modern Python type hinting practices. Usingtupleandlistinstead oftyping.Tupleandtyping.Listsimplifies the code and leverages newer Python features.package/PartSegCore/analysis/batch_processing/batch_backend.py (2)
38-38: LGTM: Type annotation updates improve code readability.The changes to import statements and type aliases are in line with modern Python type hinting practices. Using built-in types like
list,tuple, anddictinstead of theirtypingmodule counterparts simplifies the code and leverages features available in Python 3.9+.Also applies to: 96-98
Line range hint
1-1000: Overall impact: Minor type hinting improvements with no functional changes.The changes in this file are limited to updating type hints and import statements. These modifications improve code readability and align with modern Python practices without altering the core functionality of the batch processing system. The update ensures compatibility with Python 3.9+ type hinting features.
To ensure no unintended changes were made, let's verify the file contents:
package/PartSeg/_roi_analysis/advanced_window.py (3)
52-52: LGTM: Type hint updates align with modern Python syntax.The changes to type hints for
_DialogTypeandchosen_element_areaare consistent with the PR objective of updating type annotations to use Python 3.9+ syntax. This modernization improves code readability and leverages the latest Python features.Also applies to: 369-369
844-844: LGTM: Consistent type hint update in MultipleInput class.The type hint update for the
objects_listparameter in theMultipleInputclass constructor is consistent with the earlier changes and aligns with the PR objective of modernizing type annotations.
Line range hint
1-944: Summary: Type hint updates enhance code modernity and readability.The changes in this file focus on updating type hints to use built-in types instead of those from the
typingmodule. These updates are consistent with the PR's objective of modernizing the codebase for Python 3.9+. The changes improve code readability and leverage newer Python features without altering the functionality of the code.Key points:
- Type hints for
_DialogType,chosen_element_area, andobjects_listhave been updated.- The changes are syntactic and don't affect runtime behavior.
- The updates are minimal and focused, reducing the risk of introducing new bugs.
Overall, these changes represent a positive step towards maintaining a modern and readable codebase.
package/PartSeg/_roi_analysis/prepare_plan_widget.py (6)
297-299: LGTM: Updated type annotation to use built-inlist.The change from
typing.List[str]tolist[str]is correct and aligns with modern Python type hinting practices (Python 3.9+). This update improves code readability while maintaining the same meaning.
305-306: LGTM: Consistent update of type annotation.The change from
typing.List[str]tolist[str]is correct and consistent with the previous update. This maintains code consistency and readability throughout the file.
320-321: LGTM: Updated type annotation for dictionary using built-indict.The change from
typing.Dict[str, SaveBase]todict[str, SaveBase]is correct and consistent with the previous updates. This change improves code readability and aligns with modern Python type hinting practices.
643-644: LGTM: Updated type annotation for set using built-inset.The change from
typing.Set[str]toset[str]is correct and consistent with the previous updates. This change continues to improve code readability and maintain consistency with modern Python type hinting practices.
693-694: LGTM: Consistent update of type annotation for dictionary.The change from
typing.Dict[str, SaveBase]todict[str, SaveBase]is correct and consistent with the previous updates in this file. This change maintains code consistency across different classes and improves overall readability.
Line range hint
1-1252: Summary: Successful migration to modern type hinting syntax.The changes made in this file consistently update type annotations from the
typingmodule to use built-in types (e.g.,list,dict,set). These updates improve code readability and align with modern Python type hinting practices available in Python 3.9+. The changes are consistent with the PR objective of dropping support for Python 3.8 and utilizing modern Python syntax.Key points:
- All changes maintain the same semantic meaning as the original annotations.
- The updates are applied consistently across different classes and methods.
- No logical or functional changes were made, focusing solely on type annotation updates.
These changes contribute to a more maintainable and future-proof codebase.
package/PartSegCore/analysis/measurement_calculation.py (12)
3-3: Improved import specificityThe import statement has been updated to include specific items from
collections.abc. This is a good practice as it improves code readability and potentially performance by importing only the necessary items.
84-84: Updated type hint to Python 3.9+ syntaxThe type hint for
components_translationhas been updated to use the new Python 3.9+ syntax. This change improves readability and aligns with modern Python practices without affecting functionality.
94-96: Updated type hints to Python 3.9+ syntaxThe type hints for
MeasurementValueType,MeasurementResultType, andMeasurementResultInputTypehave been updated to use Python 3.9+ syntax. This change improves code consistency and readability without affecting functionality.
110-111: Updated type hints in MeasurementResult classThe type hints for
_units_dictand_type_dictin theMeasurementResultclass have been updated to use Python 3.9+ syntax. This change improves code consistency and readability without affecting functionality.
160-160: Updated return type hint in get_component_info methodThe return type hint in the
get_component_infomethod has been updated to use Python 3.9+ syntax. This change improves code consistency and readability without affecting functionality.
171-171: Updated return type hint in get_labels methodThe return type hint in the
get_labelsmethod has been updated to use Python 3.9+ syntax. This change improves code consistency and readability without affecting functionality.
189-189: Updated return type hint in get_units methodThe return type hint in the
get_unitsmethod has been updated to use Python 3.9+ syntax. This change improves code consistency and readability without affecting functionality.
267-267: Updated type hint in MeasurementProfile classThe type hint for
chosen_fieldsin theMeasurementProfileclass has been updated to use Python 3.9+ syntax. This change improves code consistency and readability without affecting functionality.
287-287: Updated return type hint in _get_par_component_and_area_type methodThe return type hint in the
_get_par_component_and_area_typemethod has been updated to use Python 3.9+ syntax. This change improves code consistency and readability without affecting functionality.
481-482: Updated return type hint in calculate_tree methodThe return type hint in the
calculate_treemethod has been updated to use Python 3.9+ syntax. This change improves code consistency and readability without affecting functionality.
1561-1561: Updated type hint in Haralick classThe type hint for
help_dictin theHaralickclass has been updated to use Python 3.9+ syntax. This change improves code consistency and readability without affecting functionality.
Line range hint
1-1761: Summary of type hint updatesThis pull request successfully updates the type hints in the
measurement_calculation.pyfile to use Python 3.9+ syntax. The changes include:
- Replacing
Listwithlist- Replacing
Dictwithdict- Replacing
TuplewithtupleThese updates improve code readability and maintainability while ensuring compatibility with newer Python versions. The changes are consistent throughout the file and do not affect the functionality of the code.
package/PartSegImage/channel_class.py (1)
Line range hint
30-38: Ensure consistent function signatures for Pydantic validatorsThe function
check_type_has different signatures based on the Pydantic version:
- For Pydantic 2:
def check_type_(value, _validation_info=None, **_):- For Pydantic 1:
def check_type_(value):While this adapts to the changes in Pydantic's validation interface, it's important to verify that these signatures are correct and consistent with Pydantic's expectations.
Run the following script to confirm the validator signatures required by Pydantic:
Ensure that the function signatures align with Pydantic's API to prevent potential validation issues.
✅ Verification successful
Validator function signatures are consistent with the supported Pydantic versions.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check Pydantic validator signatures in your codebase. # Search for all custom validators and their signatures. rg --type py -A 2 'def __get_validators__\(' # Search for Pydantic's documentation on validator signatures. # Note: Since access to external URLs is not possible, ensure you've checked Pydantic's official docs. echo "Please verify the validator signature requirements in Pydantic's documentation."Length of output: 392
Script:
#!/bin/bash # Description: Retrieve all definitions of check_type_ and their signatures. # Find all occurrences of 'def check_type_' and display the function definitions. rg --type py 'def check_type_\('Length of output: 217
Script:
#!/bin/bash # Description: Find the Pydantic version specified in the project's dependencies. # Search common dependency files for Pydantic version rg --files-with-matches 'pydantic==' requirements.txt pyproject.toml setup.py || echo "Pydantic version not specified in requirements.txt, pyproject.toml, or setup.py."Length of output: 305
Script:
#!/bin/bash # Description: Search the entire codebase for any Pydantic version specifications. # Search for 'pydantic==' in all files to find version specifications rg 'pydantic==' . # Additionally, search for 'Pydantic' version mentions in documentation or comments rg -i 'pydantic.*version' .Length of output: 2533
package/PartSegCore/mask_create.py (3)
Line range hint
105-122: Good use of built-in generic types in type annotations.The update from
typing.List[int]tolist[int]and similar changes in thecalculate_maskfunction enhance readability and leverage Python 3.9+ features. This modernizes the codebase effectively.
176-176: Consistent use ofIteratorfromcollections.abc.As previously noted, consider replacing
typing.IteratorwithIteratorfromcollections.abcto maintain consistency with the use of built-in generic types.
232-232: Efficient use of built-in generic types for sets.The type annotation for
border_sethas been correctly updated to useset[int], which aligns with Python 3.9+ syntax. This improves readability and consistency.package/PartSegCore/class_generator.py (1)
367-367: Update aligns with Python 3.9+ type hinting standardsThe change from
typing.Tupletotuplein the return type annotation ofas_tupleleverages the built-in generic types introduced in Python 3.9. This modernization simplifies the type hints and is appropriate given the project's shift to Python 3.9+.package/PartSegCore/algorithm_describe_base.py (4)
7-7: Updated Imports Align with Python 3.9+ StandardsThe imports of
MutableMappingfromcollections.abcandAnnotatedfromtypingare appropriate and align with Python 3.9+ syntax.Also applies to: 10-10
208-208: Type Annotation Updated to Use Built-indictThe return type in
get_fields_dictnow uses the built-indicttype, which is appropriate for Python 3.9+.
242-245: Type Annotations Updated for Modern SyntaxThe updates to
AlgorithmTypeand theRegisterclass appropriately use modern type annotations, enhancing code clarity.
539-540: Updated Use ofMutableMappingThe use of
MutableMappingfromcollections.abcin the_pretty_printmethod is appropriate and aligns with Python 3.9+ standards.package/PartSegCore/segmentation/restartable_segmentation_algorithms.py (1)
199-199: LGTM! Return type annotation updated appropriately.The return type annotation has been correctly updated to use the built-in
dicttype with Python 3.9+ syntax.package/PartSeg/_roi_mask/main_window.py (1)
890-890: Approve the updated type annotation forget_setting_class.The change from
Type[StackSettings]totype[StackSettings]is appropriate. With Python 3.9+, the built-intypecan be parameterized directly, aligning with PEP 585 enhancements. This update removes the need to importTypefrom thetypingmodule and modernizes the codebase.package/PartSeg/common_gui/napari_image_view.py (11)
4-4: Update import of 'MutableMapping'The import of
MutableMappinghas been correctly updated tofrom collections.abc import MutableMapping, which is appropriate for Python 3.9+ and consistent with the move away from thetypingmodule for this import.
117-117: Use of built-in generic types for 'ColorInfo'The type alias
ColorInfonow uses built-in generic types:dict,list, andOptional. This aligns with Python 3.9+ syntax and improves code readability.
123-124: Modernized type annotations in 'ImageInfo' classThe type annotations for
layersandfilter_infohave been updated to use built-inlistandtupletypes. This change utilizes Python 3.9+ features and enhances code clarity.
132-132: Updated parameter type hints to use built-in 'list'The
coords_inmethod now useslist[int]instead ofList[int]for thecoordsparameter, reflecting modern Python 3.9+ type hinting practices.
139-139: Updated parameter type hints to use built-in 'list'Similarly, the
translated_coordsmethod has updated thecoordsparameter tolist[int], aligning with Python 3.9+ syntax.
638-638: Use of built-in 'tuple' in 'calculate_filter'The
calculate_filtermethod now uses the built-intupletype for theparametersargument, which is appropriate for Python 3.9+ and enhances type hint consistency.
684-684: Updated type hint for '_add_image' methodThe
image_dataparameter in the_add_imagemethod now usestuple[ImageInfo, bool], adopting the built-intupletype for clarity and consistency with Python 3.9+.
772-772: Updated return type in 'images_bounds' methodThe return type is now specified as
tuple[list[int], list[int]], utilizing built-in generic types for improved readability and compatibility with Python 3.9+.
988-988: Updated return type in '_bounding_box' methodThe
_bounding_boxmethod's return type has been updated toOptional[tuple[np.ndarray, np.ndarray]], correctly using the built-intupletype.
1073-1077: Refined type annotations in 'ImageParameters' dataclassThe
ImageParametersdataclass attributes now use built-in generic types:
limits: list[tuple[float, float]]visibility: list[bool]gamma: list[float]colormaps: list[Colormap]scaling: tuple[Union[float, int]]These changes enhance code conciseness and are consistent with Python 3.9+ conventions.
1081-1081: Updated return type for '_prepare_layers' functionThe return type of
_prepare_layersis nowtuple[ImageInfo, bool], aligning with the use of built-intuplefor type annotations in Python 3.9+.package/PartSeg/common_backend/base_argparser.py (3)
8-8: Properly updated import of 'Sequence' from 'collections.abc'Importing
Sequencefromcollections.abcis appropriate for Python 3.9 and above, as these abstractions were moved fromtypingtocollections.abcin Python 3.9. This modernizes the codebase and aligns with the updated Python standards.
11-11: Retaining 'Optional' import from 'typing' is correctThe continued import of
Optionalfrom thetypingmodule is correct, asOptionalremains part oftypingin Python 3.9+. This ensures that type annotations remain accurate and the code stays compatible with type checkers.
Line range hint
49-51: Addition of type annotations to the 'parse_args' method enhances clarityAdding type annotations to the
parse_argsmethod improves code readability and leverages static type checking tools. SpecifyingargsasOptional[Sequence[str]]clearly communicates the expected input type.
| python_version: "3.10" | ||
| os: ${{ matrix.os }} | ||
| napari: "napari5" | ||
| napari: "napari54" |
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.
💡 Codebase verification
Update Required: Workflow is not using the latest stable napari release.
The workflow is currently using napari54 mapped to v0.4.18, while the latest stable release of napari is 0.5.4. To ensure that tests are run against the most recent stable version, consider updating the workflow to use napari 0.5.4.
- Update
.github/workflows/test_napari_widgets.ymlto usenapari: "0.5.4"
🔗 Analysis chain
Approve update to latest napari version.
The update from "napari5" to "napari54" for the latest release test is appropriate and aligns with the PR objective of updating dependencies.
To ensure we're testing against the most recent stable release, please run the following script:
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.
Where napari5.4 is mapped to v0.4.18?
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.
@Czaki, thank you for bringing this to my attention. I apologize for the confusion.
You're correct—napari54 corresponds to napari version 0.5.4, not v0.4.18 as I previously mentioned.
Therefore, your workflow is already using the latest stable release of napari, and no update is necessary.
✏️ Learnings added
Learnt from: Czaki
PR: 4DNucleome/PartSeg#1206
File: .github/workflows/test_napari_widgets.yml:30-30
Timestamp: 2024-10-17T12:19:43.676Z
Learning: In the CI configuration, `napari54` corresponds to napari version `0.5.4`.
Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
| @@ -1,4 +1,4 @@ | |||
| from typing import Callable, List, Optional, Tuple, Union | |||
| from typing import Callable, Optional, Union | |||
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.
💡 Codebase verification
Remaining imports and usages of List and Tuple found in the codebase
The script identified multiple files where List and Tuple are still imported from the typing module or used in type annotations. Please update these occurrences to use the built-in list and tuple types instead.
examples/dev/cut_images_on_part.pypackage/tests/conftest.pypackage/PartSeg/_roi_mask/batch_proceed.pypackage/tests/test_PartSeg/test_common_gui.pypackage/tests/test_PartSeg/test_io.pypackage/PartSeg/common_gui/image_adjustment.pypackage/PartSeg/common_backend/base_settings.pypackage/PartSeg/common_gui/custom_save_dialog.pypackage/PartSeg/common_gui/custom_load_dialog.pypackage/PartSeg/plugins/modeling_save/save_modeling_data.pypackage/PartSeg/plugins/old_partseg/old_partseg.pypackage/tests/test_PartSeg/test_base_widgets.pypackage/tests/test_PartSegCore/test_io.pypackage/tests/test_PartSegCore/test_napari_plugins.pypackage/tests/test_PartSegCore/test_pipeline.pypackage/tests/test_PartSeg/roi_analysis/test_main_window.pypackage/tests/test_PartSeg/roi_mask/test_main_window.pypackage/PartSeg/_roi_mask/stack_settings.pypackage/tests/test_PartSegCore/test_analysis_batch.pypackage/PartSeg/_roi_mask/main_window.pypackage/PartSeg/_roi_analysis/main_window.pypackage/PartSeg/plugins/itk_snap_save/__init__.pypackage/PartSeg/_roi_analysis/partseg_settings.pypackage/PartSegImage/image_reader.pypackage/PartSegCore/roi_info.pypackage/PartSegCore/io_utils.pypackage/PartSegCore/class_generator.pypackage/PartSegCore/napari_plugins/loader.pypackage/PartSegCore/mask/io_functions.pypackage/PartSegCore/mask/history_utils.pypackage/PartSegCore/analysis/__init__.pypackage/PartSegCore/analysis/save_functions.pypackage/PartSegCore/napari_plugins/save_mask_roi.pypackage/PartSegCore/analysis/measurement_calculation.pypackage/PartSegCore/analysis/load_functions.pypackage/PartSegCore/analysis/io_utils.pypackage/PartSegCore/analysis/batch_processing/batch_backend.py
🔗 Analysis chain
Verify removal of List and Tuple imports across the codebase
The import statement for List and Tuple has been correctly removed from this file. To ensure consistency across the entire project, it's important to verify that this change has been applied uniformly where necessary.
Run the following script to check for any remaining imports of List and Tuple from the typing module:
If any results are found, please update those occurrences to use the built-in list and tuple types instead.
Re-run import checks without using the --type python flag
The previous script failed because rg does not recognize python as a file type. Please execute the following updated script to verify the removal of List and Tuple imports across the codebase:
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check for remaining imports of List and Tuple from typing module
# Test: Search for imports of List or Tuple from typing. Expect: No results if all have been updated.
rg --type python 'from typing import .*(?:List|Tuple)'
# Test: Search for uses of List or Tuple without import. Expect: No results if all have been updated.
rg --type python '\b(?:List|Tuple)\[' -g '!test_*.py'
Length of output: 174
Script:
#!/bin/bash
# Description: Check for remaining imports of List and Tuple from the typing module
# Test: Search for imports of List or Tuple from typing. Expect: No results if all have been updated.
rg 'from typing import .*List|Tuple' -g '*.py'
# Test: Search for uses of List or Tuple without import. Expect: No results if all have been updated.
rg '\b(?:List|Tuple)\[' -g '*.py' -g '!test_*.py'
Length of output: 18393
| self.viewer = viewer | ||
|
|
||
| def _label_show(self, name: str, label: List[Sequence[float]], removable) -> LabelShow: | ||
| def _label_show(self, name: str, label: list[Sequence[float]], removable) -> LabelShow: |
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.
LGTM! Consider adding Python version comment and fixing typo in class name.
The change from List[Sequence[float]] to list[Sequence[float]] is consistent with the previous update and aligns with modern Python type hinting practices.
- Consider adding a comment indicating the minimum Python version required for this syntax:
def _label_show(self, name: str, label: list[Sequence[float]], removable) -> LabelShow: # Python 3.9+- There appears to be a typo in the class name "NaparliLabelChoose". Did you mean "NapariLabelChoose"?
If the class name is indeed a typo, please update it throughout the file:
-class NaparliLabelChoose(LabelChoose):
+class NapariLabelChoose(LabelChoose):Make sure to update any references to this class name in other parts of the codebase as well.
|
|
||
|
|
||
| def register(target: Type[AlgorithmDescribeBase], target_type: RegisterEnum, replace=False, old_names=None): | ||
| def register(target: type[AlgorithmDescribeBase], target_type: RegisterEnum, replace=False, old_names=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.
💡 Codebase verification
Update remaining type hints for consistency
The register.py file still uses Dict for type hints. To maintain consistency with modern Python type hinting practices, replace Dict with the built-in dict. For example:
base_class_dict: dict # Replace Dict with dict🔗 Analysis chain
LGTM! Consider updating other type hints for consistency.
The change from Type[AlgorithmDescribeBase] to type[AlgorithmDescribeBase] is correct and aligns with modern Python type hinting practices (PEP 585). This update improves code readability and leverages built-in types for annotations.
Consider updating other type hints in this file to use the new style consistently. For example, replace Dict with dict in the comments and any other type hints.
Please ensure that any CI tools or type checkers in your pipeline are compatible with this new type hint syntax. Run the following command to check for other occurrences of typing module usage that could be updated:
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
rg --type python 'from\s+typing\s+import' package/PartSegCore/register.py
Length of output: 406
Script:
#!/bin/bash
# Check if the file exists
if [ -f package/PartSegCore/register.py ]; then
echo "File exists: package/PartSegCore/register.py"
else
echo "File does not exist: package/PartSegCore/register.py"
fi
# List all Python files in the directory
fd --extension py . package/PartSegCore/
Length of output: 3217
Script:
#!/bin/bash
# Search for 'from typing import' without specifying the file type
echo "Searching for 'from typing import' in package/PartSegCore/register.py:"
rg 'from\s+typing\s+import' package/PartSegCore/register.py
# List all supported file types in rg
echo "\nListing all supported file types in ripgrep:"
rg --type-list
Length of output: 5143
Script:
#!/bin/bash
# Search for 'from typing import' using the correct type identifier 'py'
echo "Searching for 'from typing import' in package/PartSegCore/register.py using type 'py':"
rg --type py 'from\s+typing\s+import' package/PartSegCore/register.py
# Search for other deprecated type hints that could be replaced with built-in types
echo "\nSearching for old-style type hints (Dict, List, Tuple, Set, Type) in package/PartSegCore/register.py:"
rg --type py '\b(Dict|List|Tuple|Set|FrozenSet|Type)\b' package/PartSegCore/register.py
Length of output: 664
| - task: UsePythonVersion@0 | ||
| inputs: | ||
| versionSpec: '3.9' | ||
| versionSpec: '3.11' |
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.
💡 Codebase verification
Potential Compatibility Issues with Python 3.11
The update to Python 3.11 may introduce compatibility issues due to existing version-specific checks in the codebase:
-
Test Skipping for Python >= 3.10:
pytest.mark.skipif(sys.version_info >= (3, 10), reason="class register is not compatible with python 3.10+")
-
Version Requirements:
@pytest.mark.skipif(sys.version_info < (3, 9), reason="requires python 3.9 or higher")if sys.version_info < (3, 10):if sys.version_info[:3] != (3, 9, 7):if sys.version_info[:3] == (3, 9, 7):
These checks indicate that the code is not currently designed to support Python versions above 3.10, which includes the proposed 3.11 update.
Action Items:
- Update Version Constraints: Modify the existing
sys.version_infochecks to include support for Python 3.11. - Dependency Verification: Ensure all project dependencies are compatible with Python 3.11.
- Comprehensive Testing: Run the full test suite in a Python 3.11 environment to identify and address any compatibility issues.
🔗 Analysis chain
Approved: Python version update in GetTestData stage
The update from Python 3.9 to 3.11 in the GetTestData stage is consistent with the PR objective of dropping support for older Python versions. This change could potentially improve performance and allow the use of newer Python features.
To ensure this change doesn't introduce any compatibility issues, please verify:
- All dependencies used in the
GetTestDatastage are compatible with Python 3.11. - The artifacts produced by this stage (TestData and ReleaseInfo) are still compatible with the downstream stages that depend on them.
You can use the following script to check for any Python version-specific code or dependencies in the repository:
This script will help identify any potential compatibility issues that might arise from updating the Python version.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check for Python version-specific code or dependencies
# Search for version-specific imports or syntax
echo "Checking for version-specific Python code:"
rg --type python 'import.*python3\.(8|9|10)' || echo "No version-specific imports found."
# Check requirements files for version-specific dependencies
echo "Checking requirements files for version-specific dependencies:"
rg --type-add 'requirements:*.txt' --type requirements '^python_version' || echo "No version-specific dependencies found in requirements files."
# Check for sys.version_info checks
echo "Checking for sys.version_info checks:"
rg --type python 'sys\.version_info' || echo "No sys.version_info checks found."
Length of output: 826
Script:
#!/bin/bash
# Description: Check for Python version-specific code or dependencies
# Search for version-specific imports or syntax in Python files
echo "Checking for version-specific Python code:"
rg --glob '*.py' 'import.*python3\.(8|9|10)' || echo "No version-specific imports found."
# Check requirements files for version-specific dependencies
echo "Checking requirements files for version-specific dependencies:"
rg --glob 'requirements*.txt' '^python_version' || echo "No version-specific dependencies found in requirements files."
# Check for sys.version_info checks in Python files
echo "Checking for sys.version_info checks:"
rg --glob '*.py' 'sys\.version_info' || echo "No sys.version_info checks found."
Length of output: 1278
| @classmethod | ||
| @_partial_abstractmethod | ||
| def get_fields(cls) -> typing.List[typing.Union[AlgorithmProperty, str]]: | ||
| def get_fields(cls) -> list[typing.Union[AlgorithmProperty, str]]: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Simplify Type Annotations by Importing Union Directly
The return type in get_fields uses typing.Union. For enhanced readability, consider importing Union directly from typing.
Apply this change:
+from typing import Union
def get_fields(cls) -> list[typing.Union[AlgorithmProperty, str]]:Updated line:
def get_fields(cls) -> list[Union[AlgorithmProperty, str]]:|
|
||
|
|
||
| def get_fields_from_algorithm(ald_desc: AlgorithmDescribeBase) -> typing.List[typing.Union[AlgorithmProperty, str]]: | ||
| def get_fields_from_algorithm(ald_desc: AlgorithmDescribeBase) -> list[typing.Union[AlgorithmProperty, str]]: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Simplify Type Annotations by Importing Union Directly
Similar to previous suggestions, consider importing Union directly for the return type of get_fields_from_algorithm.
Apply this change:
+from typing import Union
def get_fields_from_algorithm(ald_desc: AlgorithmDescribeBase) -> list[typing.Union[AlgorithmProperty, str]]:Updated line:
def get_fields_from_algorithm(ald_desc: AlgorithmDescribeBase) -> list[Union[AlgorithmProperty, str]]:| def register( | ||
| self, value: AlgorithmType, replace: bool = False, old_names: typing.Optional[typing.List[str]] = None | ||
| ): | ||
| def register(self, value: AlgorithmType, replace: bool = False, old_names: typing.Optional[list[str]] = 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.
🛠️ Refactor suggestion
Simplify Type Annotations by Importing Optional Directly
In the register method, consider importing Optional directly to simplify the type annotation of old_names.
Apply this change:
+from typing import Optional
def register(self, value: AlgorithmType, replace: bool = False, old_names: typing.Optional[list[str]] = None):Updated line:
def register(self, value: AlgorithmType, replace: bool = False, old_names: Optional[list[str]] = None):|
|
||
| name: str | ||
| values: typing.Union[typing.Dict[str, typing.Any], PydanticBaseModel] = Field(..., union_mode="left_to_right") | ||
| values: typing.Union[dict[str, typing.Any], PydanticBaseModel] = Field(..., union_mode="left_to_right") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Simplify Type Annotations by Importing Union and Any Directly
For better readability, consider importing Union and Any directly and updating the type annotation of values.
Apply this change:
+from typing import Any, Union
values: typing.Union[dict[str, typing.Any], PydanticBaseModel] = Field(..., union_mode="left_to_right")Updated line:
values: Union[dict[str, Any], PydanticBaseModel] = Field(..., union_mode="left_to_right")| @classmethod | ||
| def register( | ||
| cls, value: AlgorithmType, replace=False, old_names: typing.Optional[typing.List[str]] = None | ||
| cls, value: AlgorithmType, replace=False, old_names: typing.Optional[list[str]] = 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.
🛠️ Refactor suggestion
Simplify Type Annotations by Importing Optional Directly
In the class method register, consider importing Optional directly for consistency.
Apply this change:
+from typing import Optional
def register(cls, value: AlgorithmType, replace=False, old_names: typing.Optional[list[str]] = None) -> AlgorithmType:Updated line:
def register(cls, value: AlgorithmType, replace=False, old_names: Optional[list[str]] = None) -> AlgorithmType:
|



Python 3.8 reached EOL so it is time to drop it.
Summary by Sourcery
Drop support for Python 3.8 across the codebase and CI configuration. Update type annotations to use modern Python syntax and refactor code for improved readability and consistency.
Enhancements:
CI:
Summary by CodeRabbit
New Features
Bug Fixes
Chores