Skip to content

Commit

Permalink
[BE] enable ruff rule RSE and remove useless parentheses in `rais…
Browse files Browse the repository at this point in the history
…e` statements (pytorch#124261)

Remove useless parentheses in `raise` statements if the exception type is raised with no argument.

Pull Request resolved: pytorch#124261
Approved by: https://github.com/albanD
  • Loading branch information
XuehaiPan authored and pytorchmergebot committed Apr 17, 2024
1 parent b726a23 commit 93e2499
Show file tree
Hide file tree
Showing 98 changed files with 297 additions and 296 deletions.
4 changes: 2 additions & 2 deletions benchmarks/dynamo/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -1858,7 +1858,7 @@ class TimeOutException(Exception):


def alarm_handler(signum, frame):
raise TimeOutException()
raise TimeOutException


def exit_after(s):
Expand Down Expand Up @@ -2136,7 +2136,7 @@ def skip_models_due_to_control_flow(self):
return set()

def get_tolerance_and_cosine_flag(self, is_training, current_device, name):
raise NotImplementedError()
raise NotImplementedError

@property
def equal_nan(self):
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/dynamo/microbenchmarks/operator_inp_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def serialize_sparse_tensor(e):


def deserialize_sparse_tensor(size, dtype, layout, is_coalesced, nnz=None):
raise NotImplementedError()
raise NotImplementedError


def deserialize_tensor(size, dtype, stride=None):
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ select = [
"PT025",
"PT026",
"PYI",
"RSE",
"RUF008", # mutable dataclass default
"RUF015", # access first ele in constant time
"RUF016", # type error non-integer index
Expand Down
2 changes: 1 addition & 1 deletion scripts/release_notes/commitlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -578,7 +578,7 @@ def main():
with open(filename, "w") as f:
f.writelines(lines)
return
raise AssertionError()
raise AssertionError


if __name__ == "__main__":
Expand Down
4 changes: 2 additions & 2 deletions test/cpp/jit/tests_setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@

class Setup:
def setup(self):
raise NotImplementedError()
raise NotImplementedError

def shutdown(self):
raise NotImplementedError()
raise NotImplementedError


class FileSetup:
Expand Down
8 changes: 4 additions & 4 deletions test/distributed/checkpoint/e2e/test_fsdp_ep.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def __init__(self):
super().__init__()

def forward(self, x):
raise NotImplementedError()
raise NotImplementedError


class EPModel(nn.Module):
Expand All @@ -31,7 +31,7 @@ def __init__(self, rank):
self.net2 = nn.Sequential(nn.Linear(16, 16), nn.ReLU())

def forward(self, x):
raise NotImplementedError()
raise NotImplementedError


class SecondTier(nn.Module):
Expand All @@ -43,7 +43,7 @@ def __init__(self, rank):
self.net = nn.Sequential(nn.Linear(16, 16), nn.ReLU())

def forward(self, x):
raise NotImplementedError()
raise NotImplementedError


class TopModel(nn.Module):
Expand All @@ -55,7 +55,7 @@ def __init__(self, rank):
self.net = nn.Sequential(nn.Linear(16, 16), nn.ReLU())

def forward(self, x):
raise NotImplementedError()
raise NotImplementedError


class TestFSDPWithEP(DTensorTestBase, VerifyStateDictMixin):
Expand Down
4 changes: 2 additions & 2 deletions test/distributed/elastic/metrics/api_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def emit(self, metric_data: MetricData):
class Parent(abc.ABC):
@abc.abstractmethod
def func(self):
raise NotImplementedError()
raise NotImplementedError

def base_func(self):
self.func()
Expand All @@ -57,7 +57,7 @@ def bar(self):

@prof
def throw(self):
raise RuntimeError()
raise RuntimeError

@prof(group="torchelastic")
def bar2(self):
Expand Down
2 changes: 1 addition & 1 deletion test/distributed/elastic/rendezvous/api_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ def get_backend(self) -> str:
return "dummy_backend"

def next_rendezvous(self) -> Tuple[Store, int, int]:
raise NotImplementedError()
raise NotImplementedError

def is_closed(self) -> bool:
return False
Expand Down
2 changes: 1 addition & 1 deletion test/distributed/elastic/utils/distributed_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def _create_c10d_store_mp(is_server, server_addr, port, world_size, wait_for_wor
timeout=2,
)
if store is None:
raise AssertionError()
raise AssertionError

store.set(f"test_key/{os.getpid()}", b"test_value")

Expand Down
2 changes: 1 addition & 1 deletion test/distributed/fsdp/test_fsdp_optim_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,7 @@ def _init_transformer_model(
# these settings are not implemented since the transformer is
# wrapped with FSDP at the top-level, which means that there is
# only a single flat parameter, making these booleans vacuous
raise NotImplementedError()
raise NotImplementedError
if group is None:
group = dist.distributed_c10d._get_default_group()
model = TransformerWithSharedParams.init(
Expand Down
2 changes: 1 addition & 1 deletion test/distributed/pipeline/sync/test_bugs.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def forward(self, x):

class Raise(nn.Module):
def forward(self, x):
raise ExpectedException()
raise ExpectedException

model = nn.Sequential(Pass(), Pass(), Raise())
model = Pipe(model, chunks=3)
Expand Down
4 changes: 2 additions & 2 deletions test/distributed/pipeline/sync/test_pipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ class ExpectedException(Exception):

class Raise(nn.Module):
def forward(self, *_):
raise ExpectedException()
raise ExpectedException

model = nn.Sequential(Raise())
model = Pipe(model, chunks=1)
Expand Down Expand Up @@ -265,7 +265,7 @@ def forward(self, x):

class Raise(nn.Module):
def forward(self, x):
raise ExpectedException()
raise ExpectedException

model = nn.Sequential(Pass(), Pass(), Counter(), Raise())
model = Pipe(model, chunks=3)
Expand Down
2 changes: 1 addition & 1 deletion test/dynamo/test_autograd_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -752,7 +752,7 @@ def __torch_dispatch__(cls, func, types, args, kwargs=None):
new_data = args[0]._data.view(*args[1:])
return FooTensor(new_data, args[0]._config, args[0]._scale)

raise NotImplementedError()
raise NotImplementedError

class foo_autograd_fn(torch.autograd.Function):
@staticmethod
Expand Down
10 changes: 5 additions & 5 deletions test/dynamo/test_exc.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def fn001(x):
def test_internal_error_suppress_errors(self, records):
def fn001(x):
def f(ctx):
raise AssertionError()
raise AssertionError

comptime(f)

Expand All @@ -62,7 +62,7 @@ def f(ctx):
========== TorchDynamo Stack Trace ==========
Traceback (most recent call last):
File "test_exc.py", line N, in f
raise AssertionError()
raise AssertionError
AssertionError:
from user code:
Expand All @@ -84,7 +84,7 @@ def f(ctx):
def test_not_implemented_error(self, records):
def fn001(x):
def f(ctx):
raise NotImplementedError()
raise NotImplementedError

# Ensure graph break is not possible
for i in range(3):
Expand All @@ -101,7 +101,7 @@ def f(ctx):
due to:
Traceback (most recent call last):
File "test_exc.py", line N, in f
raise NotImplementedError()
raise NotImplementedError
torch._dynamo.exc.InternalTorchDynamoError:
from user code:
Expand All @@ -128,7 +128,7 @@ def fn001(x):
# NB: avoid decorator, as 3.11 changed the line number attributed
# in this situation
def f(ctx):
raise AssertionError()
raise AssertionError

comptime(f)

Expand Down
4 changes: 2 additions & 2 deletions test/dynamo/test_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ def test_inductor_error(self, records):
import torch._inductor.lowering

def throw(x):
raise AssertionError()
raise AssertionError

# inject an error in the lowerings
dict_entries = {}
Expand All @@ -189,7 +189,7 @@ def throw(x):
due to:
Traceback (most recent call last):
File "test_logging.py", line N, in throw
raise AssertionError()
raise AssertionError
torch._dynamo.exc.BackendCompilerFailed: backend='inductor' raised:
LoweringException: AssertionError:
target: aten.round.default
Expand Down
12 changes: 6 additions & 6 deletions test/dynamo/test_repros.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,12 +396,12 @@ def __next__(self) -> Any:
if self.resolve:
x = x._dereference_node()
if x._is_missing():
raise AssertionError()
raise AssertionError

self.index = self.index + 1
if isinstance(x, ListConfig.ValueNode):
return x._value()
raise AssertionError()
raise AssertionError

def __iter__(self):
return self._iter_ex(True)
Expand All @@ -410,7 +410,7 @@ def _iter_ex(self, resolve: bool) -> Iterator[Any]:
try:
return ListConfig.ListIterator(self, resolve)
except Exception:
raise AssertionError()
raise AssertionError

def __init__(self):
self._content = [
Expand Down Expand Up @@ -545,7 +545,7 @@ def apply_chunking_to_forward(forward_fn, *input_tensors):
assert all(input_tensor.shape[1] == tensor_shape for input_tensor in input_tensors)
num_args_in_forward_chunk_fn = len(inspect.signature(forward_fn).parameters)
if num_args_in_forward_chunk_fn != len(input_tensors):
raise ValueError()
raise ValueError

return forward_fn(*input_tensors)

Expand Down Expand Up @@ -848,7 +848,7 @@ def _merge_criteria_processor_list(default_list, custom_list):
for default in default_list:
for custom in custom_list:
if type(custom) is type(default):
raise ValueError()
raise ValueError
default_list.extend(custom_list)
return default_list

Expand Down Expand Up @@ -2573,7 +2573,7 @@ def __next__(self):
if self.i < 3:
self.i += 1
return self.i
raise StopIteration()
raise StopIteration

@torch.compile(backend="eager", fullgraph=True)
def fn(x):
Expand Down
4 changes: 2 additions & 2 deletions test/dynamo/test_skip_non_tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,10 +147,10 @@ def fn(x):

class Foo(list):
def __iter__(self):
raise Exception()
raise Exception

def __len__(self):
raise Exception()
raise Exception

x = Foo()
x.append(torch.randn(4))
Expand Down
2 changes: 1 addition & 1 deletion test/dynamo/test_structured_trace.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ def test_inductor_error(self):
import torch._inductor.lowering

def throw(x):
raise AssertionError()
raise AssertionError

# inject an error in the lowerings
dict_entries = {}
Expand Down
6 changes: 3 additions & 3 deletions test/functorch/discover_coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -732,12 +732,12 @@ def no_opinfos_skip_test(self, test_name):

def any_opinfo_attr(self, attr):
if not self.has_opinfo():
raise RuntimeError()
raise RuntimeError
return any(getattr(opinfo, attr) for opinfo in self.opinfos)

def all_opinfo_attr(self, attr):
if not self.has_opinfo():
raise RuntimeError()
raise RuntimeError
return all(getattr(opinfo, attr) for opinfo in self.opinfos)

def supports_vjp(self):
Expand Down Expand Up @@ -870,7 +870,7 @@ def all(cls):
elif n.startswith(torch_dot):
names_sanitized.append(n[len(torch_dot) :])
else:
raise AssertionError()
raise AssertionError
return cls.from_names(names_sanitized)

def query(self, operator_method, filter=(Support.NO, Support.YES, Support.UNKNOWN)):
Expand Down
4 changes: 2 additions & 2 deletions test/functorch/test_dims.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,7 @@ def test_hello(self):
# test with too many elements
try:
A[1, ..., 1, 1]
raise NotImplementedError()
raise NotImplementedError
except IndexError:
pass
c, d = dims()
Expand All @@ -415,7 +415,7 @@ def test_hello(self):
)
try:
A[..., 3, ...]
raise NotImplementedError()
raise NotImplementedError
except DimensionBindError:
pass

Expand Down
4 changes: 2 additions & 2 deletions test/inductor/test_torchinductor_dynamic_shapes.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ def test_item_to_inputs_kernel_nobreak(self, device):

@custom_ops.custom_op("test::foo")
def foo(x: torch.Tensor, y: int) -> torch.Tensor:
raise NotImplementedError()
raise NotImplementedError

@custom_ops.impl("test::foo")
def foo_impl(x: torch.Tensor, y: int) -> torch.Tensor:
Expand Down Expand Up @@ -401,7 +401,7 @@ def test_dynamic_stride_nobreak(self, device):

@custom_ops.custom_op("test::foo")
def foo(x: torch.Tensor) -> torch.Tensor:
raise NotImplementedError()
raise NotImplementedError

@custom_ops.impl("test::foo")
def foo_impl(x: torch.Tensor) -> torch.Tensor:
Expand Down
2 changes: 1 addition & 1 deletion test/jit/test_freezing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2632,7 +2632,7 @@ def forward(self, in_tensor1, in_tensor2, cond: bool):
res3 = torch._C._nn.linear(in_tensor2, self.w2, self.b2)
res4 = torch._C._nn.linear(in_tensor1, self.w2, self.b1)
else:
raise AssertionError()
raise AssertionError
res2 = torch._C._nn.linear(in_tensor1, self.w2, self.b1)
return res1, res2, res3, res4

Expand Down
2 changes: 1 addition & 1 deletion test/jit/test_list_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -2871,7 +2871,7 @@ def __iter__(self):

def __next__(self):
if self.value == limit: # noqa: F821
raise StopIteration()
raise StopIteration

ret = self.value
self.value += 1
Expand Down
Loading

0 comments on commit 93e2499

Please sign in to comment.