Skip to content

Commit

Permalink
🔨 Remove try-except-pass pattern
Browse files Browse the repository at this point in the history
🔨  ruff error 738
  • Loading branch information
arafune committed Oct 20, 2023
1 parent 0b793c7 commit f6f9f79
Show file tree
Hide file tree
Showing 10 changed files with 112 additions and 36 deletions.
34 changes: 29 additions & 5 deletions arpes/endstations/plugin/fallback.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,31 @@
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

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 "
Expand Down Expand Up @@ -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,
Expand All @@ -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"]
Expand Down
28 changes: 20 additions & 8 deletions arpes/endstations/plugin/kaindl.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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(
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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(
Expand All @@ -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"}

Expand Down
18 changes: 16 additions & 2 deletions arpes/endstations/plugin/merlin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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."""
Expand Down Expand Up @@ -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",
Expand Down
22 changes: 17 additions & 5 deletions arpes/load_pxt.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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(
Expand Down Expand Up @@ -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
],
Expand Down Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion arpes/plotting/annotations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
9 changes: 5 additions & 4 deletions arpes/plotting/dynamic_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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()
Expand Down
17 changes: 15 additions & 2 deletions arpes/plotting/qt_tool/BinningInfoWidget.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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."""
Expand Down Expand Up @@ -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)=}")
4 changes: 2 additions & 2 deletions arpes/plotting/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = (
Expand Down
13 changes: 7 additions & 6 deletions arpes/widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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)
Expand Down
1 change: 0 additions & 1 deletion tests/test_qt.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down

0 comments on commit f6f9f79

Please sign in to comment.