Skip to content

Commit 31e0127

Browse files
Apply non esentail parts of better serialization PR #462 (#533)
Co-authored-by: Sourcery AI <> Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
1 parent dd95a47 commit 31e0127

26 files changed

Lines changed: 516 additions & 287 deletions

.github/workflows/test_prereleases.yml

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -69,21 +69,10 @@ jobs:
6969
7070
- name: Test with tox linux
7171
# run tests using pip install --pre
72-
if: runner.os == 'Linux'
7372
uses: GabrielBB/xvfb-action@v1
7473
timeout-minutes: 60
7574
with:
76-
run: tox -v --pre
77-
env:
78-
PLATFORM: ${{ matrix.platform }}
79-
PYVISTA_OFF_SCREEN: True # required for opengl on windows
80-
NAPARI: None
81-
82-
- name: Test with tox linux
83-
# run tests using pip install --pre
84-
if: runner.os != 'Linux'
85-
timeout-minutes: 60
86-
run: tox -v --pre
75+
run: python -m tox -v --pre
8776
env:
8877
PLATFORM: ${{ matrix.platform }}
8978
PYVISTA_OFF_SCREEN: True # required for opengl on windows

.github/workflows/tests.yml

Lines changed: 4 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -74,21 +74,10 @@ jobs:
7474
7575
- name: Test with tox linux
7676
# run tests using pip install --pre
77-
if: runner.os == 'Linux'
7877
uses: GabrielBB/xvfb-action@v1
7978
timeout-minutes: 60
8079
with:
81-
run: tox
82-
env:
83-
PLATFORM: ${{ matrix.platform }}
84-
PYVISTA_OFF_SCREEN: True # required for opengl on windows
85-
NAPARI: None
86-
87-
- name: Test with tox linux
88-
# run tests using pip install --pre
89-
if: runner.os != 'Linux'
90-
timeout-minutes: 60
91-
run: tox
80+
run: python -m tox
9281
env:
9382
PLATFORM: ${{ matrix.platform }}
9483
PYVISTA_OFF_SCREEN: True # required for opengl on windows
@@ -136,7 +125,7 @@ jobs:
136125
# run tests using pip install --pre
137126
uses: GabrielBB/xvfb-action@v1
138127
with:
139-
run: tox -e py38-PyQt5-all
128+
run: python -m tox -e py38-PyQt5-all
140129
timeout-minutes: 60
141130

142131
test_coverage:
@@ -168,7 +157,7 @@ jobs:
168157
- name: Test with tox
169158
uses: GabrielBB/xvfb-action@v1
170159
with:
171-
run: tox -e py38-PyQt5-coverage
160+
run: python -m tox -e py38-PyQt5-coverage
172161
timeout-minutes: 60
173162

174163
- uses: codecov/codecov-action@v1
@@ -200,5 +189,5 @@ jobs:
200189
- name: Test with tox
201190
uses: GabrielBB/xvfb-action@v1
202191
with:
203-
run: tox -e py37-PyQt5-minimal
192+
run: python -m tox -e py37-PyQt5-minimal
204193
timeout-minutes: 60

MANIFEST.in

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,4 @@ exclude dist/**
3838
exclude dist/**.swp
3939
exclude cliff.toml
4040
exclude runtime.txt
41+
exclude .sourcery.yaml

package/PartSeg/_roi_analysis/main_window.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,7 @@ def save_profile(self):
278278
QMessageBox.No,
279279
):
280280
continue
281-
resp = ROIExtractionProfile(text, widget.name, widget.get_values())
281+
resp = ROIExtractionProfile(name=text, algorithm=widget.name, values=widget.get_values())
282282
self._settings.roi_profiles[text] = resp
283283
self._settings.dump()
284284
break

package/PartSeg/_roi_analysis/prepare_plan_widget.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -468,9 +468,9 @@ def change_segmentation_table(self):
468468
index = self.segment_stack.currentIndex()
469469
text = self.segment_stack.tabText(index)
470470
if self.update_element_chk.isChecked():
471-
self.chose_profile_btn.setText("Replace " + text)
471+
self.chose_profile_btn.setText(f"Replace {text}")
472472
else:
473-
self.chose_profile_btn.setText("Add " + text)
473+
self.chose_profile_btn.setText(f"Add {text}")
474474
self.segment_profile.setCurrentItem(None)
475475
self.pipeline_profile.setCurrentItem(None)
476476

@@ -800,9 +800,12 @@ def refresh_profiles(self, list_widget: QListWidget, new_values: typing.List[str
800800

801801
@contextmanager
802802
def enable_protect(self):
803+
previous = self.protect
803804
self.protect = True
804-
yield
805-
self.protect = False
805+
try:
806+
yield
807+
finally:
808+
self.protect = previous
806809

807810
def _refresh_measurement(self):
808811
new_measurements = list(sorted(self.settings.measurement_profiles.keys(), key=str.lower))
@@ -1125,7 +1128,7 @@ def delete_plan(self):
11251128
if self.calculate_plans.currentItem() is None:
11261129
return
11271130
text = str(self.calculate_plans.currentItem().text())
1128-
if text == "":
1131+
if not text:
11291132
return
11301133
if text in self.settings.batch_plans:
11311134
del self.settings.batch_plans[text]
@@ -1135,7 +1138,7 @@ def edit_plan(self):
11351138
if self.calculate_plans.currentItem() is None:
11361139
return
11371140
text = str(self.calculate_plans.currentItem().text())
1138-
if text == "":
1141+
if not text:
11391142
return
11401143
if text in self.settings.batch_plans:
11411144
self.plan_to_edit = self.settings.batch_plans[text]

package/PartSeg/_roi_mask/simple_measurements.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ def calculate(self):
8484
QMessageBox.warning(self, "No measurement", "Select at least one measurement")
8585
return
8686

87-
profile = MeasurementProfile("", [MeasurementEntry(x.name, x) for x in to_calculate])
87+
profile = MeasurementProfile("", [MeasurementEntry(name=x.name, calculation_tree=x) for x in to_calculate])
8888

8989
dial = ExecuteFunctionDialog(
9090
profile.calculate,

package/PartSeg/common_backend/base_argparser.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,9 @@ def proper_suffix(val: str):
2525
2626
:raise argparse.ArgumentTypeError: on validation error
2727
"""
28-
if len(val) > 0 and not val.isalnum():
29-
raise argparse.ArgumentTypeError(f"suffix '{val}' need to contains only alpha numeric characters")
30-
return val
28+
if not val or val.isalnum():
29+
return val
30+
raise argparse.ArgumentTypeError(f"suffix '{val}' need to contains only alpha numeric characters")
3131

3232

3333
def proper_path(val: str):
@@ -40,8 +40,9 @@ def proper_path(val: str):
4040
return val
4141
try:
4242
os.makedirs(val)
43-
except OSError:
44-
raise argparse.ArgumentTypeError(f" Path {val} is not a valid path in this system")
43+
except OSError as e:
44+
raise argparse.ArgumentTypeError(f" Path {val} is not a valid path in this system") from e
45+
4546
return val
4647

4748

@@ -105,8 +106,9 @@ def parse_args(self, args: Optional[Sequence[str]] = None, namespace: Optional[a
105106
state_store.develop = args.develop
106107
state_store.save_suffix = args.save_suffix[0]
107108
state_store.save_folder = os.path.abspath(
108-
args.save_directory[0] + ("_" + state_store.save_suffix if state_store.save_suffix else "")
109+
args.save_directory[0] + (f"_{state_store.save_suffix}" if state_store.save_suffix else "")
109110
)
111+
110112
if args.no_report and args.no_dialog:
111113
_setup_sentry()
112114
sys.excepthook = my_excepthook
@@ -129,6 +131,4 @@ def _setup_sentry(): # pragma: no cover
129131

130132

131133
def safe_repr(val):
132-
if isinstance(val, np.ndarray):
133-
return numpy_repr(val)
134-
return _safe_repr(val)
134+
return numpy_repr(val) if isinstance(val, np.ndarray) else _safe_repr(val)

package/PartSeg/common_backend/base_settings.py

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -176,8 +176,8 @@ def roi(self, val: Union[np.ndarray, ROIInfo]):
176176
self._roi_info = ROIInfo(self.image.fit_array_to_image(val))
177177
else:
178178
self._roi_info = val.fit_to_image(self.image)
179-
except ValueError:
180-
raise ValueError(ROI_NOT_FIT)
179+
except ValueError as e:
180+
raise ValueError(ROI_NOT_FIT) from e
181181
self._additional_layers = {}
182182
self.roi_changed.emit(self._roi_info)
183183

@@ -540,8 +540,8 @@ def set_segmentation_result(self, result: ROIExtractionResult):
540540
# Fixme not use EventedDict here
541541
try:
542542
roi_info = result.roi_info.fit_to_image(self.image)
543-
except ValueError: # pragma: no cover
544-
raise ValueError(ROI_NOT_FIT)
543+
except ValueError as e: # pragma: no cover
544+
raise ValueError(ROI_NOT_FIT) from e
545545
if result.points is not None:
546546
self.points = result.points
547547
self._roi_info = roi_info
@@ -601,8 +601,8 @@ def mask(self, value):
601601
try:
602602
self._image.set_mask(value)
603603
self.mask_changed.emit()
604-
except ValueError:
605-
raise ValueError("mask do not fit to image")
604+
except ValueError as e:
605+
raise ValueError("mask do not fit to image") from e
606606

607607
def get_save_list(self) -> List[SaveSettingsDescription]:
608608
"""List of files in which program save the state."""
@@ -618,7 +618,7 @@ def get_path_history(self) -> List[str]:
618618
"""
619619
res = self.get(DIR_HISTORY, [])[:]
620620
for name in self.save_locations_keys:
621-
val = self.get("io." + name, str(Path.home()))
621+
val = self.get(f"io.{name}", str(Path.home()))
622622
if val not in res:
623623
res = res + [val]
624624
return res
@@ -698,9 +698,7 @@ def load_part(cls, file_path):
698698
data = cls.load_metadata(file_path)
699699
bad_key = []
700700
if isinstance(data, MutableMapping) and not check_loaded_dict(data):
701-
for k, v in data.items():
702-
if not check_loaded_dict(v):
703-
bad_key.append(k)
701+
bad_key.extend(k for k, v in data.items() if not check_loaded_dict(v))
704702
for el in bad_key:
705703
del data[el]
706704
elif isinstance(data, ProfileDict) and not data.verify_data():
@@ -762,7 +760,7 @@ def load(self, folder_path: Union[Path, str, None] = None):
762760
if error:
763761
timestamp = datetime.today().strftime("%Y-%m-%d_%H_%M_%S")
764762
base_path, ext = os.path.splitext(file_path)
765-
os.rename(file_path, base_path + "_" + timestamp + ext)
763+
os.rename(file_path, f"{base_path}_{timestamp}{ext}")
766764

767765
if errors_list:
768766
logger.error(errors_list)

package/PartSeg/common_gui/algorithms_description.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -467,12 +467,9 @@ def algorithm_choose(self, name):
467467
if name not in self.property.possible_values:
468468
return
469469
start_dict = {} if name not in self.starting_values else self.starting_values[name]
470-
try:
471-
self.widgets_dict[name] = FormWidget(
472-
self.property.possible_values[name].get_fields(), start_values=start_dict
473-
)
474-
except KeyError as e:
475-
raise e
470+
self.widgets_dict[name] = FormWidget(
471+
self.property.possible_values[name].get_fields(), start_values=start_dict
472+
)
476473
self.widgets_dict[name].layout().setContentsMargins(0, 0, 0, 0)
477474
self.layout().addWidget(self.widgets_dict[name])
478475
self.widgets_dict[name].value_changed.connect(self.values_changed)
@@ -633,7 +630,7 @@ def enable_selector(self):
633630
el.setEnabled(True)
634631

635632
def get_segmentation_profile(self) -> ROIExtractionProfile:
636-
return ROIExtractionProfile("", self.algorithm.get_name(), self.get_values())
633+
return ROIExtractionProfile(name="", algorithm=self.algorithm.get_name(), values=self.get_values())
637634

638635

639636
class AlgorithmChooseBase(QWidget):
@@ -738,7 +735,7 @@ def current_widget(self) -> InteractiveAlgorithmSettingsWidget:
738735

739736
def current_parameters(self) -> ROIExtractionProfile:
740737
widget = self.current_widget()
741-
return ROIExtractionProfile("", widget.name, widget.get_values())
738+
return ROIExtractionProfile(name="", algorithm=widget.name, values=widget.get_values())
742739

743740
def get_info_text(self):
744741
return self.current_widget().algorithm_thread.get_info_text()

package/PartSeg/plugins/napari_widgets/roi_extraction_algorithms.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ def save_action(self):
172172
QMessageBox.No,
173173
):
174174
break # pragma: no cover
175-
resp = ROIExtractionProfile(text, widget.name, widget.get_values())
175+
resp = ROIExtractionProfile(name=text, algorithm=widget.name, values=widget.get_values())
176176
profiles[text] = resp
177177
self.settings.dump()
178178
self.profile_combo_box.addItem(text)

0 commit comments

Comments
 (0)