From 7e7436cda5c017a0e79084baa39fa05b026ecf9b Mon Sep 17 00:00:00 2001 From: Jinzhe Zeng Date: Tue, 9 Jul 2024 22:40:14 -0400 Subject: [PATCH] style: enable B904 (#3956) As planned in https://github.com/deepmodeling/deepmd-kit/pull/3933#discussion_r1661577543 ## Summary by CodeRabbit - **Bug Fixes** - Improved exception handling across multiple modules to provide more context in error messages. - **Chores** - Added rule `B904` for `raise-without-from-inside-except` to `pyproject.toml`. These changes enhance debugging by offering clearer error messages and context, thus improving the overall user experience when dealing with exceptions. Signed-off-by: Jinzhe Zeng --- backend/find_tensorflow.py | 2 +- deepmd/dpmodel/descriptor/descriptor.py | 6 ++++-- deepmd/entrypoints/neighbor_stat.py | 4 ++-- deepmd/pt/model/descriptor/descriptor.py | 6 ++++-- deepmd/utils/data_system.py | 4 ++-- pyproject.toml | 1 + source/tests/common/test_argument_parser.py | 8 ++++---- source/tests/tf/test_parallel_training.py | 4 ++-- 8 files changed, 20 insertions(+), 15 deletions(-) diff --git a/backend/find_tensorflow.py b/backend/find_tensorflow.py index 06452ab1f5..514490a926 100644 --- a/backend/find_tensorflow.py +++ b/backend/find_tensorflow.py @@ -102,7 +102,7 @@ def find_tensorflow() -> Tuple[Optional[str], List[str]]: ) tf_version = "2.14.1" else: - raise RuntimeError("Unsupported CUDA version") + raise RuntimeError("Unsupported CUDA version") from None requires.extend(get_tf_requirement(tf_version)["cpu"]) # setuptools will re-find tensorflow after installing setup_requires tf_install_dir = None diff --git a/deepmd/dpmodel/descriptor/descriptor.py b/deepmd/dpmodel/descriptor/descriptor.py index aa9db1e96b..3e0ad13420 100644 --- a/deepmd/dpmodel/descriptor/descriptor.py +++ b/deepmd/dpmodel/descriptor/descriptor.py @@ -39,8 +39,10 @@ def __new__(cls, *args, **kwargs): if cls is DescriptorBlock: try: descrpt_type = kwargs["type"] - except KeyError: - raise KeyError("the type of DescriptorBlock should be set by `type`") + except KeyError as e: + raise KeyError( + "the type of DescriptorBlock should be set by `type`" + ) from e cls = cls.get_class_by_type(descrpt_type) return super().__new__(cls) diff --git a/deepmd/entrypoints/neighbor_stat.py b/deepmd/entrypoints/neighbor_stat.py index ef02561ba3..87ec101c70 100644 --- a/deepmd/entrypoints/neighbor_stat.py +++ b/deepmd/entrypoints/neighbor_stat.py @@ -75,8 +75,8 @@ def neighbor_stat( backends = Backend.get_backends_by_feature(Backend.Feature.NEIGHBOR_STAT) try: backend_obj = backends[backend]() - except KeyError: - raise ValueError(f"Invalid backend {backend}") + except KeyError as e: + raise ValueError(f"Invalid backend {backend}") from e NeighborStat = backend_obj.neighbor_stat all_sys = expand_sys_str(system) if not len(all_sys): diff --git a/deepmd/pt/model/descriptor/descriptor.py b/deepmd/pt/model/descriptor/descriptor.py index 0f0d87fe86..a552d1adec 100644 --- a/deepmd/pt/model/descriptor/descriptor.py +++ b/deepmd/pt/model/descriptor/descriptor.py @@ -48,8 +48,10 @@ def __new__(cls, *args, **kwargs): if cls is DescriptorBlock: try: descrpt_type = kwargs["type"] - except KeyError: - raise KeyError("the type of DescriptorBlock should be set by `type`") + except KeyError as e: + raise KeyError( + "the type of DescriptorBlock should be set by `type`" + ) from e cls = cls.get_class_by_type(descrpt_type) return super().__new__(cls) diff --git a/deepmd/utils/data_system.py b/deepmd/utils/data_system.py index f02398278f..92782a7274 100644 --- a/deepmd/utils/data_system.py +++ b/deepmd/utils/data_system.py @@ -196,8 +196,8 @@ def __init__( words = self.test_size.split("%") try: percent = int(words[0]) - except ValueError: - raise RuntimeError("unknown test_size rule " + words[0]) + except ValueError as e: + raise RuntimeError("unknown test_size rule " + words[0]) from e self.test_size = self._make_auto_ts(percent) elif isinstance(self.test_size, list): pass diff --git a/pyproject.toml b/pyproject.toml index 1c5dd51878..89508252de 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -344,6 +344,7 @@ select = [ "TID251", # banned-api "TID253", # banned-module-level-imports "T20", # ban print + "B904", # raise-without-from-inside-except ] ignore = [ diff --git a/source/tests/common/test_argument_parser.py b/source/tests/common/test_argument_parser.py index 674025c307..36a2f07be5 100644 --- a/source/tests/common/test_argument_parser.py +++ b/source/tests/common/test_argument_parser.py @@ -157,13 +157,13 @@ def run_test(self, *, command: str, mapping: "TEST_DICT"): try: with redirect_stderr(buffer): namespace = parse_args(cmd_args) - except SystemExit: + except SystemExit as e: raise SystemExit( f"Encountered expection when parsing arguments ->\n\n" f"{buffer.getvalue()}\n" f"passed in arguments were: {cmd_args}\n" f"built from dict {mapping}" - ) + ) from e self.attr_and_type_check(namespace, mapping, command, test_value=True) # check for required arguments @@ -189,13 +189,13 @@ def run_test(self, *, command: str, mapping: "TEST_DICT"): try: with redirect_stderr(buffer): namespace = parse_args(cmd_args) - except SystemExit: + except SystemExit as e: raise SystemExit( f"Encountered expection when parsing DEFAULT arguments ->\n\n" f"{buffer.getvalue()}\n" f"passed in arguments were: {cmd_args}\n" f"built from dict {mapping}" - ) + ) from e self.attr_and_type_check(namespace, mapping, command, test_value=False) def test_no_command(self): diff --git a/source/tests/tf/test_parallel_training.py b/source/tests/tf/test_parallel_training.py index d190764695..13346a2c30 100644 --- a/source/tests/tf/test_parallel_training.py +++ b/source/tests/tf/test_parallel_training.py @@ -16,10 +16,10 @@ class TestSingleMachine(unittest.TestCase): def setUp(self): try: import horovod # noqa: F401 - except ImportError: + except ImportError as e: raise unittest.SkipTest( "Package horovod is required for parallel-training tests." - ) + ) from e self.input_file = str(tests_path / "model_compression" / "input.json") def test_two_workers(self):