Skip to content

Commit

Permalink
style: enable B904 (#3956)
Browse files Browse the repository at this point in the history
As planned in
#3933 (comment)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## 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.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Signed-off-by: Jinzhe Zeng <[email protected]>
  • Loading branch information
njzjz authored Jul 10, 2024
1 parent 623ddc7 commit b86165d
Show file tree
Hide file tree
Showing 8 changed files with 20 additions and 15 deletions.
2 changes: 1 addition & 1 deletion backend/find_tensorflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 4 additions & 2 deletions deepmd/dpmodel/descriptor/descriptor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
4 changes: 2 additions & 2 deletions deepmd/entrypoints/neighbor_stat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
6 changes: 4 additions & 2 deletions deepmd/pt/model/descriptor/descriptor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
4 changes: 2 additions & 2 deletions deepmd/utils/data_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,7 @@ select = [
"TID251", # banned-api
"TID253", # banned-module-level-imports
"T20", # ban print
"B904", # raise-without-from-inside-except
]

ignore = [
Expand Down
8 changes: 4 additions & 4 deletions source/tests/common/test_argument_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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):
Expand Down
4 changes: 2 additions & 2 deletions source/tests/tf/test_parallel_training.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down

0 comments on commit b86165d

Please sign in to comment.