From 16ec2007d10fb7a5a011a83a8c586e0ffe435bd9 Mon Sep 17 00:00:00 2001 From: Jean-Claude Graf Date: Tue, 9 Feb 2021 13:57:32 +0100 Subject: [PATCH] IMPROVE: Propagate exceptions - Propagate KeyError from KeyHandler - Do not catch UnsupportedMetadataOperation in metadatawidget since it will never be thrown - Fix lint --- vimiv/gui/metadatawidget.py | 16 +++------ vimiv/imutils/metadata.py | 67 ++++++++++++++++++------------------- vimiv/version.py | 3 +- 3 files changed, 39 insertions(+), 47 deletions(-) diff --git a/vimiv/gui/metadatawidget.py b/vimiv/gui/metadatawidget.py index 2ec0ae7d7..69ff35431 100644 --- a/vimiv/gui/metadatawidget.py +++ b/vimiv/gui/metadatawidget.py @@ -121,12 +121,8 @@ def metadata_list_keys(self, n_cols: int = 3, to_term: bool = False): * ``--to-term``: Print the keys to the terminal instead. """ - try: - keys = sorted(set(self.handler.get_keys())) - _logger.debug("Successfully got keys") - except metadata.UnsupportedMetadataOperation: - # TODO: should actually never happen - pass + keys = sorted(set(self.handler.get_keys())) + _logger.debug("Successfully got keys") if to_term: print(*keys, sep="\n") elif n_cols < 1: @@ -166,12 +162,8 @@ def _update_text(self): e.strip() for e in api.settings.metadata.current_keyset.value.split(",") ] _logger.debug(f"Read metadata.current_keys {keys}") - try: - data = self.handler.fetch_keys(keys) - _logger.debug("Fetched metadata") - except data.UnsupportedMetadataOperation: - # TODO: should never happen - pass + data = self.handler.fetch_keys(keys) + _logger.debug("Fetched metadata") if data: self.setText(utils.format_html_table(data.values())) diff --git a/vimiv/imutils/metadata.py b/vimiv/imutils/metadata.py index e2e45b652..a53df23b0 100644 --- a/vimiv/imutils/metadata.py +++ b/vimiv/imutils/metadata.py @@ -68,16 +68,16 @@ def _get_ydimension(self): return self.reader.size().height() def __getitem__(self, key: str) -> Tuple[str, str, str]: - """Intrypoint to extract the key of the image at _path. + """Entrypoint to extract the key of the image at _path. Args: key: internal key to fetch. + + Throws: + KeyError """ - try: - key, func = super().get(key.lower()) - return (key, key, func()) - except KeyError: - return ("", "", "") + key, func = super().__getitem__(key.lower()) + return (key, key, func()) def get_keys(self) -> Iterable[str]: """Returns a sequence of all available metadata keys.""" @@ -119,6 +119,9 @@ def fetch_key(self, _base_key: str) -> Tuple[str, str, str]: Args: _base_key: metadata key to fetch. + + Throws: + KeyError """ self.raise_exception("Getting formatted keys") @@ -150,7 +153,7 @@ def __init__(self, filename=""): def fetch_key(self, base_key: str) -> Tuple[str, str, str]: key = base_key.rpartition(".")[2] - try: + with contextlib.suppress(piexif.InvalidImageDateError): for ifd in self._metadata: if ifd == "thumbnail": continue @@ -189,10 +192,7 @@ def fetch_key(self, base_key: str) -> Tuple[str, str, str]: ): # (int, int) <=> numerator, denominator return (keyname, keyname, f"{val[0]}/{val[1]}") - except (piexif.InvalidImageDataError, KeyError): - return ("", "", "") - - return ("", "", "") + raise KeyError(f"Key '{base_key}' not found") def get_keys(self) -> Iterable[str]: return ( @@ -271,28 +271,23 @@ def fetch_key(self, base_key: str) -> Tuple[str, str, str]: # For backwards compability, assume it has one of the following prefixes for prefix in ["", "Exif.Image.", "Exif.Photo."]: key = f"{prefix}{base_key}" - try: - key_name = self._metadata[key].name - - try: - key_value = self._metadata[key].human_value + key_name = self._metadata[key].name - # Not all metadata (i.e. IPTC) provide human_value, take raw_value - except AttributeError: - value = self._metadata[key].raw_value - - # For IPTC the raw_value is a list of strings - if isinstance(value, list): - key_value = ", ".join(value) - else: - key_value = value + try: + key_value = self._metadata[key].human_value - return (key, key_name, key_value) + # Not all metadata (i.e. IPTC) provide human_value, take raw_value + except AttributeError: + value = self._metadata[key].raw_value - except KeyError: - _logger.debug("Key %s is invalid for the current image", key) + # For IPTC the raw_value is a list of strings + if isinstance(value, list): + key_value = ", ".join(value) + else: + key_value = value - return ("", "", "") + return (key, key_name, key_value) + raise KeyError(f"Key '{base_key}' not found") def get_keys(self) -> Iterable[str]: """Return a iteable of all available metadata keys.""" @@ -361,10 +356,11 @@ def _external_handler(self) -> ExternalKeyHandler: def fetch_keys(self, desired_keys: Sequence[str]) -> Dict[Any, Tuple[str, str]]: """Extracts a list of metadata keys. - Throws: UnsupportedMetadataOperation. - Args: desired_keys: list of metadata keys to extract. + + Throws: + UnsupportedMetadataOperation """ metadata = dict() @@ -382,10 +378,12 @@ def fetch_keys(self, desired_keys: Sequence[str]) -> Dict[Any, Tuple[str, str]]: def fetch_key(self, key: str) -> Tuple[str, str, str]: """Extracts a single metadata key. - Throws: UnsupportedMetadataOperation. - Args: key: single metadata key to extract. + + Throws: + UnsupportedMetadataOperation + KeyError """ if key.lower().startswith("vimiv"): return self._internal_handler[key] @@ -394,7 +392,8 @@ def fetch_key(self, key: str) -> Tuple[str, str, str]: def get_keys(self) -> Iterable[str]: """Retrieve the name of all metadata keys available. - Throws: UnsupportedMetadataOperation + Throws: + UnsupportedMetadataOperation """ return itertools.chain( self._internal_handler.get_keys(), self._external_handler.get_keys() diff --git a/vimiv/version.py b/vimiv/version.py index d5cf0d958..b6e0e6c9c 100644 --- a/vimiv/version.py +++ b/vimiv/version.py @@ -42,7 +42,8 @@ def info() -> str: f"Qt: {QT_VERSION_STR}\n" f"PyQt: {PYQT_VERSION_STR}\n\n" f"Svg Support: {bool(QtSvg)}\n" - f"Pyexiv2: {metadata.pyexiv2.__version__ if metadata.pyexiv2 is not None else None}\n" + "Pyexiv2: " + f"{metadata.pyexiv2.__version__ if metadata.pyexiv2 is not None else None}\n" f"Piexif: {metadata.piexif.VERSION if metadata.piexif is not None else None}" )