From f6f9f79f34c537f900122d251fb6545b7657d76e Mon Sep 17 00:00:00 2001 From: Ryuichi Arafune Date: Fri, 20 Oct 2023 09:19:08 +0900 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A8=20=20Remove=20try-except-pass=20pa?= =?UTF-8?q?ttern?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🔨 ruff error 738 --- arpes/endstations/plugin/fallback.py | 34 ++++++++++++++++++--- arpes/endstations/plugin/kaindl.py | 28 ++++++++++++----- arpes/endstations/plugin/merlin.py | 18 +++++++++-- arpes/load_pxt.py | 22 ++++++++++--- arpes/plotting/annotations.py | 2 +- arpes/plotting/dynamic_tool.py | 9 +++--- arpes/plotting/qt_tool/BinningInfoWidget.py | 17 +++++++++-- arpes/plotting/utils.py | 4 +-- arpes/widgets.py | 13 ++++---- tests/test_qt.py | 1 - 10 files changed, 112 insertions(+), 36 deletions(-) diff --git a/arpes/endstations/plugin/fallback.py b/arpes/endstations/plugin/fallback.py index 061a5bb6..11d6807a 100644 --- a/arpes/endstations/plugin/fallback.py +++ b/arpes/endstations/plugin/fallback.py @@ -2,10 +2,11 @@ from __future__ import annotations import warnings +from logging import DEBUG, INFO, Formatter, StreamHandler, getLogger from typing import TYPE_CHECKING, ClassVar from arpes.endstations import EndstationBase, resolve_endstation -from arpes.trace import traceable +from arpes.trace import Trace, traceable if TYPE_CHECKING: from _typeshed import Incomplete @@ -13,6 +14,19 @@ from arpes.endstations import SCANDESC __all__ = ("FallbackEndstation",) +LOGLEVELS = (DEBUG, INFO) +LOGLEVEL = LOGLEVELS[1] +logger = getLogger(__name__) +fmt = "%(asctime)s %(levelname)s %(name)s :%(message)s" +formatter = Formatter(fmt) +handler = StreamHandler() +handler.setLevel(LOGLEVEL) +logger.setLevel(LOGLEVEL) +handler.setFormatter(formatter) +logger.addHandler(handler) +logger.propagate = False + + AUTOLOAD_WARNING = ( "PyARPES has chosen {} for your data since `location` was not specified. " "If this is not correct, ensure the `location` key is specified. Read the plugin documentation " @@ -44,7 +58,12 @@ class FallbackEndstation(EndstationBase): @classmethod @traceable - def determine_associated_loader(cls, file, scan_desc: SCANDESC, trace=None): + def determine_associated_loader( + cls, + file, + scan_desc: SCANDESC, + trace: Trace | None = None, + ) -> type: """Determines which loading plugin to use for a given piece of data. This is done by looping through loaders in a predetermined priority order, @@ -61,13 +80,18 @@ def determine_associated_loader(cls, file, scan_desc: SCANDESC, trace=None): endstation_cls = resolve_endstation(retry=False, location=location) if endstation_cls.is_file_accepted(file, scan_desc): return endstation_cls - except: - pass + except Exception as err: + logger.info(f"Exception occurs. {err=}, {type(err)=}") msg = f"PyARPES failed to find a plugin acceptable for {file}, \n\n{scan_desc}." raise ValueError(msg) - def load(self, scan_desc: SCANDESC | None = None, file: str = "", **kwargs: Incomplete): + def load( + self, + scan_desc: SCANDESC | None = None, + file: str = "", + **kwargs: Incomplete, + ): """Delegates to a dynamically chosen plugin for loading.""" if not file: file = scan_desc["file"] diff --git a/arpes/endstations/plugin/kaindl.py b/arpes/endstations/plugin/kaindl.py index ea84be90..03ddf8c4 100644 --- a/arpes/endstations/plugin/kaindl.py +++ b/arpes/endstations/plugin/kaindl.py @@ -3,6 +3,7 @@ import os import re +from logging import DEBUG, INFO, Formatter, StreamHandler, getLogger from pathlib import Path from typing import TYPE_CHECKING, ClassVar @@ -18,6 +19,18 @@ __all__ = ("KaindlEndstation",) +LOGLEVELS = (DEBUG, INFO) +LOGLEVEL = LOGLEVELS[1] +logger = getLogger(__name__) +fmt = "%(asctime)s %(levelname)s %(name)s :%(message)s" +formatter = Formatter(fmt) +handler = StreamHandler() +handler.setLevel(LOGLEVEL) +logger.setLevel(LOGLEVEL) +handler.setFormatter(formatter) +logger.addHandler(handler) +logger.propagate = False + def find_kaindl_files_associated(reference_path: Path): name_match = re.match( @@ -127,7 +140,7 @@ def resolve_frame_locations(self, scan_desc: SCANDESC | None = None): def concatenate_frames( self, - frames=list[xr.Dataset], + frames: list[xr.Dataset], scan_desc: SCANDESC | None = None, ): """Concenates frames from individual .pxt files on the Kaindl setup. @@ -163,8 +176,8 @@ def concatenate_frames( frames.sort(key=lambda x: x.coords[axis_name]) return xr.concat(frames, axis_name) - except Exception: - pass + except Exception as err: + logger.info(f"Exception occurs. {err=}, {type(err)=}") return None def postprocess_final(self, data: xr.Dataset, scan_desc: SCANDESC | None = None): @@ -212,8 +225,8 @@ def attach_attr(data, attr_name, as_name): data = attach_attr(data, "Photocurrent", "photocurrent") data = attach_attr(data, "Temperature B", "temp") data = attach_attr(data, "Temperature A", "cryotip_temp") - except FileNotFoundError as e: - print(e) + except FileNotFoundError as err: + logger.info(f"Exception occurs: {err}") if internal_match.groups(): attrs_path = str( @@ -223,9 +236,8 @@ def attach_attr(data, attr_name, as_name): try: extra = pd.read_csv(attrs_path, sep="\t", skiprows=6) data = data.assign_attrs(extra=extra.to_json()) - except Exception: - # WELP we tried - pass + except Exception as err: + logger.info(f"Exception occurs: {err=}, {type(err)=}") deg_to_rad_coords = {"theta", "beta", "phi"} diff --git a/arpes/endstations/plugin/merlin.py b/arpes/endstations/plugin/merlin.py index 1a696e00..fd01107a 100644 --- a/arpes/endstations/plugin/merlin.py +++ b/arpes/endstations/plugin/merlin.py @@ -2,6 +2,7 @@ from __future__ import annotations import re +from logging import DEBUG, INFO, Formatter, StreamHandler, getLogger from pathlib import Path from typing import TYPE_CHECKING, Any, ClassVar @@ -22,6 +23,18 @@ __all__ = ["BL403ARPESEndstation"] +LOGLEVELS = (DEBUG, INFO) +LOGLEVEL = LOGLEVELS[1] +logger = getLogger(__name__) +fmt = "%(asctime)s %(levelname)s %(name)s :%(message)s" +formatter = Formatter(fmt) +handler = StreamHandler() +handler.setLevel(LOGLEVEL) +logger.setLevel(LOGLEVEL) +handler.setFormatter(formatter) +logger.addHandler(handler) +logger.propagate = False + class BL403ARPESEndstation(SynchrotronEndstation, HemisphericalEndstation, SESEndstation): """The MERLIN ARPES Endstation at the Advanced Light Source.""" @@ -155,8 +168,9 @@ def concatenate_frames( _.coords[c] = _.attrs[c] return xr.concat(frames, axis_name, coords="different") - except Exception: - pass + except Exception as err: + logger.debug(f"Exception occurs. {err=}, {type(err)=}") + else: internal_match = re.match( r"([a-zA-Z0-9\w+_]+)_[R][0-9][0-9][0-9]\.pxt", diff --git a/arpes/load_pxt.py b/arpes/load_pxt.py index a78663b1..5dcece8a 100644 --- a/arpes/load_pxt.py +++ b/arpes/load_pxt.py @@ -4,6 +4,7 @@ import contextlib import re import warnings +from logging import DEBUG, INFO, Formatter, StreamHandler, getLogger from pathlib import Path from typing import TYPE_CHECKING, Any, Literal @@ -25,6 +26,19 @@ "find_ses_files_associated", ) +LOGLEVELS = (DEBUG, INFO) +LOGLEVEL = LOGLEVELS[1] +logger = getLogger(__name__) +fmt = "%(asctime)s %(levelname)s %(name)s :%(message)s" +formatter = Formatter(fmt) +handler = StreamHandler() +handler.setLevel(LOGLEVEL) +logger.setLevel(LOGLEVEL) +handler.setFormatter(formatter) +logger.addHandler(handler) +logger.propagate = False + + binary_header_bytes = 10 igor_wave_header_dtype = np.dtype( @@ -89,8 +103,7 @@ def read_igor_binary_wave(raw_bytes: bytes) -> xr.DataArray: wave_data = np.fromstring( raw_bytes[ - igor_wave_header_dtype.itemsize - + offset : igor_wave_header_dtype.itemsize + igor_wave_header_dtype.itemsize + offset : igor_wave_header_dtype.itemsize + n_points * point_size + offset ], @@ -252,9 +265,8 @@ def read_single_pxt( try: loaded = igor.load(reference_path, initial_byte_order=try_byte_order) break - except Exception: # pylint: disable=broad-except - # bad byte ordering probably - pass + except Exception as err: + logger.info(f"Exception occurs. {err=}, {type(err)=}") else: loaded = igor.load(reference_path, initial_byte_order=byte_order) if raw: diff --git a/arpes/plotting/annotations.py b/arpes/plotting/annotations.py index ea9fdba4..3d0e3d70 100644 --- a/arpes/plotting/annotations.py +++ b/arpes/plotting/annotations.py @@ -3,9 +3,9 @@ from typing import TYPE_CHECKING, Literal, Unpack +import matplotlib as mpl import numpy as np import xarray as xr -import matplotlib as mpl from matplotlib.axes import Axes from mpl_toolkits.mplot3d import Axes3D diff --git a/arpes/plotting/dynamic_tool.py b/arpes/plotting/dynamic_tool.py index 1a2deeeb..119b99a9 100644 --- a/arpes/plotting/dynamic_tool.py +++ b/arpes/plotting/dynamic_tool.py @@ -3,7 +3,7 @@ import inspect from collections.abc import Sized -from logging import INFO, Formatter, StreamHandler, getLogger +from logging import DEBUG, INFO, Formatter, StreamHandler, getLogger from typing import TYPE_CHECKING, Any from PySide6 import QtWidgets @@ -28,7 +28,8 @@ from arpes._typing import DataType -LOGLEVEL = INFO +LOGLEVELS = (DEBUG, INFO) +LOGLEVEL = LOGLEVELS[1] logger = getLogger(__name__) fmt = "%(asctime)s %(levelname)s %(name)s :%(message)s" formatter = Formatter(fmt) @@ -83,8 +84,8 @@ def update_data(self) -> None: try: mapped_data = self._function(self.data, **self.current_arguments) self.views["f(xy)"].setImage(mapped_data.fillna(0)) - except: - pass + except Exception as err: + logger.debug(f"Exception occurs. {err=}, {type(err)=}") def add_controls(self) -> None: specification = self.calculate_control_specification() diff --git a/arpes/plotting/qt_tool/BinningInfoWidget.py b/arpes/plotting/qt_tool/BinningInfoWidget.py index f2b385cb..5c050e21 100644 --- a/arpes/plotting/qt_tool/BinningInfoWidget.py +++ b/arpes/plotting/qt_tool/BinningInfoWidget.py @@ -1,6 +1,7 @@ """An axis binning control.""" from __future__ import annotations +from logging import DEBUG, INFO, Formatter, StreamHandler, getLogger from typing import TYPE_CHECKING from PySide6 import QtWidgets @@ -12,6 +13,18 @@ __all__ = ("BinningInfoWidget",) +LOGLEVELS = (DEBUG, INFO) +LOGLEVEL = LOGLEVELS[1] +logger = getLogger(__name__) +fmt = "%(asctime)s %(levelname)s %(name)s :%(message)s" +formatter = Formatter(fmt) +handler = StreamHandler() +handler.setLevel(LOGLEVEL) +logger.setLevel(LOGLEVEL) +handler.setFormatter(formatter) +logger.addHandler(handler) +logger.propagate = False + class BinningInfoWidget(QtWidgets.QGroupBox): """A spinbox allowing you to set the binning on different axes.""" @@ -57,5 +70,5 @@ def changeBinning(self) -> None: old_binning = self.root.binning old_binning[self.axis_index] = self.spinbox.value() self.root.binning = old_binning - except: - pass + except Exception as err: + logger.debug(f"Exception occurs: {err=}, {type(err)=}") diff --git a/arpes/plotting/utils.py b/arpes/plotting/utils.py index 03782945..14fa8965 100644 --- a/arpes/plotting/utils.py +++ b/arpes/plotting/utils.py @@ -1107,8 +1107,8 @@ def remove_colorbars(fig: Figure | None = None) -> None: ax.remove() else: remove_colorbars(plt.gcf()) - except Exception: - pass + except Exception as err: + logger.debug(f"Exception occurs: {err=}, {type(err)=}") generic_colorbarmap = ( diff --git a/arpes/widgets.py b/arpes/widgets.py index c78ad2a5..3e568942 100644 --- a/arpes/widgets.py +++ b/arpes/widgets.py @@ -32,7 +32,7 @@ import warnings from collections.abc import Sequence from functools import wraps -from logging import INFO, Formatter, StreamHandler, getLogger +from logging import DEBUG, INFO, Formatter, StreamHandler, getLogger from typing import TYPE_CHECKING, Any, TypeAlias import matplotlib as mpl @@ -80,7 +80,8 @@ "fit_initializer", ) -LOGLEVEL = INFO +LOGLEVELS = (DEBUG, INFO) +LOGLEVEL = LOGLEVELS[1] logger = getLogger(__name__) fmt = "%(asctime)s %(levelname)s %(name)s :%(message)s" formatter = Formatter(fmt) @@ -157,8 +158,8 @@ def onselect(self, verts: NDArray[np.float_]) -> None: if self._on_select is not None: self._on_select(self.ind) - except Exception: - pass + except Exception as err: + logger.debug(f"Exception occurs: {err=}, {type(err)=}") def disconnect(self) -> None: self.lasso.disconnect_events() @@ -602,8 +603,8 @@ def clamp(x: int, low: int, high: int) -> int: assert val_x != val_y set_axes(val_x, val_y) - except Exception: - pass + except Exception as err: + logger.debug(f"Exception occurs: {err=}, {type(err)=}") context["axis_button"] = Button(ax_widget_1, "Change Decomp Axes") context["axis_button"].on_clicked(on_change_axes) diff --git a/tests/test_qt.py b/tests/test_qt.py index c968aebb..4fe73068 100644 --- a/tests/test_qt.py +++ b/tests/test_qt.py @@ -1,7 +1,6 @@ """Unit test for qt related.""" from typing import TYPE_CHECKING -import pytest from PySide6 import QtCore from pytestqt.qt_compat import qt_api from pytestqt.qtbot import QtBot