Skip to content

Refactor unnecessary else / elif when if block has a return statement #4606

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .circleci/regenerate.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,18 +134,18 @@ def upload_doc_job(filter_branch):
def get_manylinux_image(cu_version):
if cu_version == "cpu":
return "pytorch/manylinux-cuda102"
elif cu_version.startswith("cu"):
if cu_version.startswith("cu"):
cu_suffix = cu_version[len("cu") :]
return f"pytorch/manylinux-cuda{cu_suffix}"
elif cu_version.startswith("rocm"):
if cu_version.startswith("rocm"):
rocm_suffix = cu_version[len("rocm") :]
return f"pytorch/manylinux-rocm:{rocm_suffix}"


def get_conda_image(cu_version):
if cu_version == "cpu":
return "pytorch/conda-builder:cpu"
elif cu_version.startswith("cu"):
if cu_version.startswith("cu"):
cu_suffix = cu_version[len("cu") :]
return f"pytorch/conda-builder:cuda{cu_suffix}"

Expand Down
8 changes: 3 additions & 5 deletions test/common_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,20 +45,18 @@ def __call__(self, object):
if isinstance(object, torch.Tensor):
return self.tensor_map_fn(object)

elif isinstance(object, dict):
if isinstance(object, dict):
mapped_dict = {}
for key, value in object.items():
mapped_dict[self(key)] = self(value)
return mapped_dict

elif isinstance(object, (list, tuple)):
if isinstance(object, (list, tuple)):
mapped_iter = []
for iter in object:
mapped_iter.append(self(iter))
return mapped_iter if not isinstance(object, tuple) else tuple(mapped_iter)

else:
return object
return object


def map_nested_tensor_object(object, tensor_map_fn):
Expand Down
7 changes: 3 additions & 4 deletions test/test_datasets.py
Original file line number Diff line number Diff line change
Expand Up @@ -1482,16 +1482,15 @@ class QMNISTTestCase(MNISTTestCase):
def _num_images(self, config):
if config["what"] == "nist":
return 3
elif config["what"] == "train":
if config["what"] == "train":
return 2
elif config["what"] == "test50k":
if config["what"] == "test50k":
# The split 'test50k' is defined as the last 50k images beginning at index 10000. Thus, we need to create
# more than 10000 images for the dataset to not be empty. Since this takes significantly longer than the
# creation of all other splits, this is excluded from the 'ADDITIONAL_CONFIGS' and is tested only once in
# 'test_num_examples_test50k'.
return 10001
else:
return 1
return 1

def _labels_file(self, config):
return f"{self._prefix(config)}-labels-idx2-int"
Expand Down
3 changes: 1 addition & 2 deletions test/test_datasets_download.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,7 @@ def add_mock(stack, name, file, **kwargs):
except AttributeError as error:
if file != "utils":
return add_mock(stack, name, "utils", **kwargs)
else:
raise pytest.UsageError from error
raise pytest.UsageError from error

if urls_and_md5s is None:
urls_and_md5s = set()
Expand Down
3 changes: 1 addition & 2 deletions test/test_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,8 +401,7 @@ def _collect_if(cond):
def _inner(test_func):
if cond:
return test_func
else:
return pytest.mark.dont_collect(test_func)
return pytest.mark.dont_collect(test_func)

return _inner

Expand Down
3 changes: 1 addition & 2 deletions test/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -557,8 +557,7 @@ def compact(tensor):
elements_per_sample = functools.reduce(operator.mul, size[1:], 1)
if elements_per_sample > 30:
return compute_mean_std(tensor)
else:
return subsample_tensor(tensor)
return subsample_tensor(tensor)

def subsample_tensor(tensor):
num_elems = tensor.size(0)
Expand Down
3 changes: 1 addition & 2 deletions test/test_onnx.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,7 @@ def ort_validate(self, onnx_io, inputs, outputs, tolerate_small_mismatch=False):
def to_numpy(tensor):
if tensor.requires_grad:
return tensor.detach().cpu().numpy()
else:
return tensor.cpu().numpy()
return tensor.cpu().numpy()

inputs = list(map(to_numpy, inputs))
outputs = list(map(to_numpy, outputs))
Expand Down
7 changes: 3 additions & 4 deletions torchvision/datasets/cityscapes.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,9 +213,8 @@ def _load_json(self, path: str) -> Dict[str, Any]:
def _get_target_suffix(self, mode: str, target_type: str) -> str:
if target_type == "instance":
return "{}_instanceIds.png".format(mode)
elif target_type == "semantic":
if target_type == "semantic":
return "{}_labelIds.png".format(mode)
elif target_type == "color":
if target_type == "color":
return "{}_color.png".format(mode)
else:
return "{}_polygons.json".format(mode)
return "{}_polygons.json".format(mode)
3 changes: 1 addition & 2 deletions torchvision/datasets/folder.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,8 +264,7 @@ def default_loader(path: str) -> Any:

if get_image_backend() == "accimage":
return accimage_loader(path)
else:
return pil_loader(path)
return pil_loader(path)


class ImageFolder(DatasetFolder):
Expand Down
11 changes: 5 additions & 6 deletions torchvision/datasets/imagenet.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,12 +91,11 @@ def load_meta_file(root: str, file: Optional[str] = None) -> Tuple[Dict[str, str

if check_integrity(file):
return torch.load(file)
else:
msg = (
"The meta file {} is not present in the root directory or is corrupted. "
"This file is automatically created by the ImageNet dataset."
)
raise RuntimeError(msg.format(file, root))
msg = (
"The meta file {} is not present in the root directory or is corrupted. "
"This file is automatically created by the ImageNet dataset."
)
raise RuntimeError(msg.format(file, root))


def _verify_archive(root: str, file: str, md5: str) -> None:
Expand Down
14 changes: 6 additions & 8 deletions torchvision/datasets/inaturalist.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,14 +211,12 @@ def category_name(self, category_type: str, category_id: int) -> str:
"""
if category_type == "full":
return self.all_categories[category_id]
else:
if category_type not in self.categories_index:
raise ValueError(f"Invalid category type '{category_type}'")
else:
for name, id in self.categories_index[category_type].items():
if id == category_id:
return name
raise ValueError(f"Invalid category id {category_id} for {category_type}")
if category_type not in self.categories_index:
raise ValueError(f"Invalid category type '{category_type}'")
for name, id in self.categories_index[category_type].items():
if id == category_id:
return name
raise ValueError(f"Invalid category id {category_id} for {category_type}")

def _check_integrity(self) -> bool:
return os.path.exists(self.root) and len(os.listdir(self.root)) > 0
Expand Down
2 changes: 1 addition & 1 deletion torchvision/datasets/stl10.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def __init__(
def _verify_folds(self, folds: Optional[int]) -> Optional[int]:
if folds is None:
return folds
elif isinstance(folds, int):
if isinstance(folds, int):
if folds in range(10):
return folds
msg = "Value for argument folds should be in the range [0, 10), " "but got {}."
Expand Down
3 changes: 1 addition & 2 deletions torchvision/io/video.py
Original file line number Diff line number Diff line change
Expand Up @@ -355,8 +355,7 @@ def _decode_video_timestamps(container: "av.container.Container") -> List[int]:
if _can_read_timestamps_from_packets(container):
# fast path
return [x.pts for x in container.demux(video=0) if x.pts is not None]
else:
return [x.pts for x in container.decode(video=0) if x.pts is not None]
return [x.pts for x in container.decode(video=0) if x.pts is not None]


def read_video_timestamps(filename: str, pts_unit: str = "pts") -> Tuple[List[int], Optional[float]]:
Expand Down
15 changes: 7 additions & 8 deletions torchvision/models/detection/backbone_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,11 +170,10 @@ def mobilenet_backbone(

in_channels_list = [backbone[stage_indices[i]].out_channels for i in returned_layers]
return BackboneWithFPN(backbone, return_layers, in_channels_list, out_channels, extra_blocks=extra_blocks)
else:
m = nn.Sequential(
backbone,
# depthwise linear combination of channels to reduce their size
nn.Conv2d(backbone[-1].out_channels, out_channels, 1),
)
m.out_channels = out_channels
return m
m = nn.Sequential(
backbone,
# depthwise linear combination of channels to reduce their size
nn.Conv2d(backbone[-1].out_channels, out_channels, 1),
)
m.out_channels = out_channels
return m
3 changes: 1 addition & 2 deletions torchvision/models/detection/generalized_rcnn.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,5 +107,4 @@ def forward(self, images, targets=None):
warnings.warn("RCNN always returns a (Losses, Detections) tuple in scripting")
self._has_warned = True
return losses, detections
else:
return self.eager_outputs(losses, detections)
return self.eager_outputs(losses, detections)
6 changes: 2 additions & 4 deletions torchvision/models/googlenet.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,8 +200,7 @@ def _forward(self, x: Tensor) -> Tuple[Tensor, Optional[Tensor], Optional[Tensor
def eager_outputs(self, x: Tensor, aux2: Tensor, aux1: Optional[Tensor]) -> GoogLeNetOutputs:
if self.training and self.aux_logits:
return _GoogLeNetOutputs(x, aux2, aux1)
else:
return x # type: ignore[return-value]
return x # type: ignore[return-value]

def forward(self, x: Tensor) -> GoogLeNetOutputs:
x = self._transform_input(x)
Expand All @@ -211,8 +210,7 @@ def forward(self, x: Tensor) -> GoogLeNetOutputs:
if not aux_defined:
warnings.warn("Scripted GoogleNet always returns GoogleNetOutputs Tuple")
return GoogLeNetOutputs(x, aux2, aux1)
else:
return self.eager_outputs(x, aux2, aux1)
return self.eager_outputs(x, aux2, aux1)


class Inception(nn.Module):
Expand Down
6 changes: 2 additions & 4 deletions torchvision/models/inception.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,8 +192,7 @@ def _forward(self, x: Tensor) -> Tuple[Tensor, Optional[Tensor]]:
def eager_outputs(self, x: Tensor, aux: Optional[Tensor]) -> InceptionOutputs:
if self.training and self.aux_logits:
return InceptionOutputs(x, aux)
else:
return x # type: ignore[return-value]
return x # type: ignore[return-value]

def forward(self, x: Tensor) -> InceptionOutputs:
x = self._transform_input(x)
Expand All @@ -203,8 +202,7 @@ def forward(self, x: Tensor) -> InceptionOutputs:
if not aux_defined:
warnings.warn("Scripted Inception3 always returns Inception3 Tuple")
return InceptionOutputs(x, aux)
else:
return self.eager_outputs(x, aux)
return self.eager_outputs(x, aux)


class InceptionA(nn.Module):
Expand Down
3 changes: 1 addition & 2 deletions torchvision/models/mnasnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,7 @@ def __init__(
def forward(self, input: Tensor) -> Tensor:
if self.apply_residual:
return self.layers(input) + input
else:
return self.layers(input)
return self.layers(input)


def _stack(
Expand Down
3 changes: 1 addition & 2 deletions torchvision/models/mobilenetv2.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,7 @@ def __init__(
def forward(self, x: Tensor) -> Tensor:
if self.use_res_connect:
return x + self.conv(x)
else:
return self.conv(x)
return self.conv(x)


class MobileNetV2(nn.Module):
Expand Down
3 changes: 1 addition & 2 deletions torchvision/models/quantization/googlenet.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,7 @@ def forward(self, x: Tensor) -> GoogLeNetOutputs:
if not aux_defined:
warnings.warn("Scripted QuantizableGoogleNet always returns GoogleNetOutputs Tuple")
return GoogLeNetOutputs(x, aux2, aux1)
else:
return self.eager_outputs(x, aux2, aux1)
return self.eager_outputs(x, aux2, aux1)

def fuse_model(self) -> None:
r"""Fuse conv/bn/relu modules in googlenet model
Expand Down
3 changes: 1 addition & 2 deletions torchvision/models/quantization/inception.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,8 +235,7 @@ def forward(self, x: Tensor) -> InceptionOutputs:
if not aux_defined:
warnings.warn("Scripted QuantizableInception3 always returns QuantizableInception3 Tuple")
return InceptionOutputs(x, aux)
else:
return self.eager_outputs(x, aux)
return self.eager_outputs(x, aux)

def fuse_model(self) -> None:
r"""Fuse conv/bn/relu modules in inception model
Expand Down
3 changes: 1 addition & 2 deletions torchvision/models/quantization/mobilenetv2.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:
def forward(self, x: Tensor) -> Tensor:
if self.use_res_connect:
return self.skip_add.add(x, self.conv(x))
else:
return self.conv(x)
return self.conv(x)

def fuse_model(self) -> None:
for idx in range(len(self.conv)):
Expand Down
3 changes: 1 addition & 2 deletions torchvision/models/quantization/mobilenetv3.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:
def forward(self, x: Tensor) -> Tensor:
if self.use_res_connect:
return self.skip_add.add(x, self.block(x))
else:
return self.block(x)
return self.block(x)


class QuantizableMobileNetV3(MobileNetV3):
Expand Down
6 changes: 2 additions & 4 deletions torchvision/ops/boxes.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,7 @@ def batched_nms(
# Ideally for GPU we'd use a higher threshold
if boxes.numel() > 4_000 and not torchvision._is_tracing():
return _batched_nms_vanilla(boxes, scores, idxs, iou_threshold)
else:
return _batched_nms_coordinate_trick(boxes, scores, idxs, iou_threshold)
return _batched_nms_coordinate_trick(boxes, scores, idxs, iou_threshold)


@torch.jit._script_if_tracing
Expand Down Expand Up @@ -210,8 +209,7 @@ def _upcast(t: Tensor) -> Tensor:
# Protects from numerical overflows in multiplications by upcasting to the equivalent higher type
if t.is_floating_point():
return t if t.dtype in (torch.float32, torch.float64) else t.float()
else:
return t if t.dtype in (torch.int32, torch.int64) else t.int()
return t if t.dtype in (torch.int32, torch.int64) else t.int()


def box_area(boxes: Tensor) -> Tensor:
Expand Down
5 changes: 2 additions & 3 deletions torchvision/prototype/datasets/_builtin/coco.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,9 @@ def _classify_meta(self, data: Tuple[str, Any]) -> Optional[int]:
key, _ = data
if key == "images":
return 0
elif key == "annotations":
if key == "annotations":
return 1
else:
return None
return None

def _decode_ann(self, ann: Dict[str, Any]) -> Dict[str, Any]:
area = torch.tensor(ann["area"])
Expand Down
5 changes: 2 additions & 3 deletions torchvision/prototype/datasets/_builtin/mnist.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,10 +272,9 @@ def _classify_archive(self, data: Tuple[str, Any], *, config: DatasetConfig) ->
(images_file, _), (labels_file, _) = self._files_and_checksums(config)
if path.name == images_file:
return 0
elif path.name == labels_file:
if path.name == labels_file:
return 1
else:
return None
return None

_LABEL_OFFSETS = {
38: 1,
Expand Down
7 changes: 3 additions & 4 deletions torchvision/prototype/datasets/_builtin/sbd.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,12 @@ def _classify_archive(self, data: Tuple[str, Any]) -> Optional[int]:

if parent.name == "dataset":
return 0
elif grandparent.name == "dataset":
if grandparent.name == "dataset":
if parent.name == "img":
return 1
elif parent.name == "cls":
if parent.name == "cls":
return 2
else:
return None
return None
else:
return None

Expand Down
7 changes: 3 additions & 4 deletions torchvision/prototype/datasets/_builtin/voc.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,11 @@ def _is_in_folder(self, data: Tuple[str, Any], *, name: str, depth: int = 1) ->
def _classify_archive(self, data: Tuple[str, Any], *, config: DatasetConfig) -> Optional[int]:
if self._is_in_folder(data, name="ImageSets", depth=2):
return 0
elif self._is_in_folder(data, name="JPEGImages"):
if self._is_in_folder(data, name="JPEGImages"):
return 1
elif self._is_in_folder(data, name=self._ANNS_FOLDER[config.task]):
if self._is_in_folder(data, name=self._ANNS_FOLDER[config.task]):
return 2
else:
return None
return None

def _decode_detection_ann(self, buffer: io.IOBase) -> torch.Tensor:
result = VOCDetection.parse_voc_xml(ElementTree.parse(buffer).getroot()) # type: ignore[arg-type]
Expand Down
Loading