Skip to content

Commit

Permalink
Check variable assignments that immediately return (#5911)
Browse files Browse the repository at this point in the history
* Check variable assignments that immediately return

* Apply suggestions from code review
  • Loading branch information
tkoyama010 committed May 15, 2024
1 parent a9a66d9 commit 1f3f47b
Show file tree
Hide file tree
Showing 30 changed files with 75 additions and 116 deletions.
3 changes: 1 addition & 2 deletions doc/source/make_external_gallery.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ def format_icon(title, link, image):
.. image:: ../images/external-examples/{}
"""
content = body.format(title, link, image)
return content
return body.format(title, link, image)


class Example:
Expand Down
29 changes: 11 additions & 18 deletions doc/source/make_tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -922,8 +922,7 @@ def _generate_carousel_badges(badges: List[_BaseDatasetBadge]):
elif isinstance(badge, _BaseDatasetBadge):
raise NotImplementedError(f'No implementation for badge type {type(badge)}.')
all_badges = module_badges + datatype_badges + special_badges + category_badges
rst = ' '.join([badge.generate() for badge in all_badges])
return rst
return ' '.join([badge.generate() for badge in all_badges])

@staticmethod
def _generate_celltype_badges(badges: List[_BaseDatasetBadge]):
Expand Down Expand Up @@ -961,8 +960,7 @@ def _format_and_indent_from_template(*args, template=None, indent_level=None):
assert template is not None
assert indent_level is not None
formatted = template.format(*args)
indented = _indent_multi_line_string(formatted, indent_level=indent_level)
return indented
return _indent_multi_line_string(formatted, indent_level=indent_level)

@classmethod
def _generate_field_grid(cls, field_name, field_values):
Expand Down Expand Up @@ -1022,22 +1020,20 @@ def _create_header_block(cls, index_name, header_name, carousel_badges):
@classmethod
def _create_image_block(cls, img_path):
"""Generate rst block for the dataset image."""
block = cls._format_and_indent_from_template(
return cls._format_and_indent_from_template(
img_path,
template=cls.image_template,
indent_level=cls.GRID_ITEM_INDENT_LEVEL,
)
return block

@classmethod
def _create_info_block(cls, func_ref, func_doc):
block = cls._format_and_indent_from_template(
return cls._format_and_indent_from_template(
func_ref,
func_doc,
template=cls.dataset_info_template,
indent_level=cls.GRID_ITEM_INDENT_LEVEL,
)
return block

@classmethod
def _create_dataset_props_block(
Expand All @@ -1061,11 +1057,10 @@ def _create_dataset_props_block(
('Spacing', spacing),
('N Arrays', n_arrays),
]
dataset_fields_block = cls._generate_field_block(
return cls._generate_field_block(
dataset_fields,
indent_level=cls.GRID_ITEM_FIELDS_INDENT_LEVEL,
)
return dataset_fields_block

@classmethod
def _create_file_props_block(cls, loader, file_size, num_files, file_ext, reader_type):
Expand All @@ -1076,11 +1071,10 @@ def _create_file_props_block(cls, loader, file_size, num_files, file_ext, reader
('File Ext', file_ext),
('Reader', reader_type),
]
file_info_fields_block = DatasetCard._generate_field_block(
return DatasetCard._generate_field_block(
file_info_fields,
indent_level=cls.GRID_ITEM_FIELDS_INDENT_LEVEL,
)
return file_info_fields_block
file_info_fields = "``Not Applicable.``\n\n``Dataset is not loaded from file.``"
return _indent_multi_line_string(
file_info_fields,
Expand All @@ -1092,12 +1086,11 @@ def _create_footer_block(cls, datasource_links):
if datasource_links:
# indent links one level from the dropdown directive in template
datasource_links = _indent_multi_line_string(datasource_links, indent_level=1)
footer_block = cls._format_and_indent_from_template(
return cls._format_and_indent_from_template(
datasource_links,
template=cls.footer_template,
indent_level=cls.HEADER_FOOTER_INDENT_LEVEL,
)
return footer_block
# Return empty footer content
return ''

Expand Down Expand Up @@ -1127,8 +1120,7 @@ def generate_file_ext(loader: Union[_SingleFilePropsProtocol, _MultiFilePropsPro
if file_ext:
file_ext = loader.unique_extension
file_ext = [file_ext] if isinstance(file_ext, str) else file_ext
file_ext = '\n'.join(['``\'' + ext + '\'``' for ext in file_ext])
return file_ext
return '\n'.join(['``\'' + ext + '\'``' for ext in file_ext])
return None

@staticmethod
Expand All @@ -1150,14 +1142,13 @@ def generate_reader_type(loader: Union[_SingleFilePropsProtocol, _MultiFileProps
@staticmethod
def generate_dataset_type(loader: _DatasetLoader):
"""Format dataset type(s) with doc references to dataset class(es)."""
dataset_type = (
return (
repr(loader.unique_dataset_type)
.replace('<class \'', ':class:`~')
.replace('\'>', '`')
.replace('(', '')
.replace(')', '')
).replace(', ', '\n')
return dataset_type

@staticmethod
def _generate_dataset_repr(loader: _DatasetLoader, indent_level: int) -> str:
Expand Down Expand Up @@ -1219,6 +1210,7 @@ def generate_dimensions(loader):
dimensions = DatasetPropsGenerator._try_getattr(loader.dataset, 'dimensions')
if dimensions:
return ', '.join([DatasetPropsGenerator._generate_number(dim) for dim in dimensions])
return None

@staticmethod
def generate_spacing(loader):
Expand All @@ -1232,6 +1224,7 @@ def generate_spacing(loader):
[DatasetPropsGenerator._generate_number(num, fmt='exp') for num in spacing],
)
return ', '.join(spacing_maybe)
return None

@staticmethod
def generate_n_arrays(loader):
Expand Down
3 changes: 1 addition & 2 deletions examples/00-load/create-point-cloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,7 @@ def generate_points(subset=0.02):
def compute_vectors(mesh):
origin = mesh.center
vectors = mesh.points - origin
vectors = vectors / np.linalg.norm(vectors, axis=1)[:, None]
return vectors
return vectors / np.linalg.norm(vectors, axis=1)[:, None]


vectors = compute_vectors(point_cloud)
Expand Down
3 changes: 1 addition & 2 deletions examples/02-plot/spherical.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,7 @@ def _cell_bounds(points, bound_position=0.5):
raise ValueError("Only 1D points are allowed.")
diffs = np.diff(points)
delta = diffs[0] * bound_position
bounds = np.concatenate([[points[0] - delta], points + delta])
return bounds
return np.concatenate([[points[0] - delta], points + delta])


# First, create some dummy data
Expand Down
3 changes: 1 addition & 2 deletions examples/03-widgets/sphere-widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,7 @@ def get_colors(n):

cycler = mpl.rcParams['axes.prop_cycle']
colors = cycle(cycler)
colors = [next(colors)['color'] for i in range(n)]
return colors
return [next(colors)['color'] for i in range(n)]


# Create a grid to interpolate to
Expand Down
6 changes: 5 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,10 @@ ignore = [
"SIM117",
# https://github.com/pyvista/pyvista/pull/5837
"SIM118",
# https://github.com/pyvista/pyvista/pull/5911
"RET505",
"RET506",
"RET507",
]
fixable = ["ALL"]
unfixable = []
Expand Down Expand Up @@ -374,7 +378,7 @@ extend-select = [
"PTH",
"PYI",
"Q",
"RET501",
"RET",
"RSE",
"RUF",
"SIM",
Expand Down
2 changes: 1 addition & 1 deletion pyvista/core/dataobject.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ def head(self, display=True, html=None):
from IPython.display import HTML, display as _display

_display(HTML(fmt))
return
return None
return fmt
# Otherwise return a string that is Python console friendly
fmt = f"{type(self).__name__} ({hex(id(self))})\n"
Expand Down
1 change: 1 addition & 0 deletions pyvista/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -2977,6 +2977,7 @@ def generate_ids(i: int, connections: str): # numpydoc ignore=GL08
return cell.get_edge(i).GetPointIds()
elif connections == "faces":
return cell.get_face(i).GetPointIds()
return None # pragma: no cover

neighbors = set()
for i in iterators[connections]:
Expand Down
23 changes: 5 additions & 18 deletions pyvista/core/filters/data_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -668,15 +668,14 @@ def clip_surface(
function.FunctionValue(points, dists)
self['implicit_distance'] = pyvista.convert_array(dists)
# run the clip
result = DataSetFilters._clip_with_function(
return DataSetFilters._clip_with_function(
self,
function,
invert=invert,
value=value,
progress_bar=progress_bar,
crinkle=crinkle,
)
return result

def slice_implicit(
self,
Expand Down Expand Up @@ -4389,8 +4388,7 @@ def sample_over_line(self, pointa, pointb, resolution=None, tolerance=None, prog
resolution = int(self.n_cells)
# Make a line and sample the dataset
line = pyvista.Line(pointa, pointb, resolution=resolution)
sampled_line = line.sample(self, tolerance=tolerance, progress_bar=progress_bar)
return sampled_line
return line.sample(self, tolerance=tolerance, progress_bar=progress_bar)

def plot_over_line(
self,
Expand Down Expand Up @@ -4549,12 +4547,7 @@ def sample_over_multiple_lines(self, points, tolerance=None, progress_bar=False)
"""
# Make a multiple lines and sample the dataset
multiple_lines = pyvista.MultipleLines(points=points)
sampled_multiple_lines = multiple_lines.sample(
self,
tolerance=tolerance,
progress_bar=progress_bar,
)
return sampled_multiple_lines
return multiple_lines.sample(self, tolerance=tolerance, progress_bar=progress_bar)

def sample_over_circular_arc(
self,
Expand Down Expand Up @@ -4633,12 +4626,7 @@ def sample_over_circular_arc(
resolution = int(self.n_cells)
# Make a circular arc and sample the dataset
circular_arc = pyvista.CircularArc(pointa, pointb, center, resolution=resolution)
sampled_circular_arc = circular_arc.sample(
self,
tolerance=tolerance,
progress_bar=progress_bar,
)
return sampled_circular_arc
return circular_arc.sample(self, tolerance=tolerance, progress_bar=progress_bar)

def sample_over_circular_arc_normal(
self,
Expand Down Expand Up @@ -6563,8 +6551,7 @@ def tessellate(self, max_n_subdivide=3, merge_points=True, progress_bar=False):
alg.SetMergePoints(merge_points)
alg.SetMaximumNumberOfSubdivisions(max_n_subdivide)
_update_alg(alg, progress_bar, 'Tessellating Mesh')
output = _get_output(alg)
return output
return _get_output(alg)

def transform(
self: _vtk.vtkDataSet,
Expand Down
6 changes: 2 additions & 4 deletions pyvista/core/filters/poly_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -343,8 +343,7 @@ def __iadd__(self, dataset):
so the in-place merge attempt will raise.
"""
merged = self.merge(dataset, inplace=True)
return merged
return self.merge(dataset, inplace=True)

def append_polydata(
self,
Expand Down Expand Up @@ -3785,8 +3784,7 @@ def reconstruct_surface(self, nbr_sz=None, sample_spacing=None, progress_bar=Fal
mc.SetInputConnection(alg.GetOutputPort())
mc.SetValue(0, 0.0)
_update_alg(mc, progress_bar, 'Reconstructing surface')
surf = wrap(mc.GetOutput())
return surf
return wrap(mc.GetOutput())

def triangulate_contours(self, display_errors=False, progress_bar=False):
"""Triangulate and fill all 2D contours to create polygons.
Expand Down
3 changes: 1 addition & 2 deletions pyvista/core/grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -821,11 +821,10 @@ def cast_to_rectilinear_grid(self) -> RectilinearGrid:
"""

def gen_coords(i): # numpydoc ignore=GL08
coords = (
return (
np.cumsum(np.insert(np.full(self.dimensions[i] - 1, self.spacing[i]), 0, 0))
+ self.origin[i]
)
return coords

xcoords = gen_coords(0)
ycoords = gen_coords(1)
Expand Down
2 changes: 1 addition & 1 deletion pyvista/core/utilities/arrays.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ def convert_array(arr, name=None, deep=False, array_type=None):
"""
if arr is None:
return
return None
if isinstance(arr, (list, tuple, str)):
arr = np.array(arr)
if isinstance(arr, np.ndarray):
Expand Down
3 changes: 1 addition & 2 deletions pyvista/core/utilities/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,7 @@ def voxelize(mesh, density=None, check_surface=True):
mask = selection.point_data['SelectedPoints'].view(np.bool_)

# extract cells from point indices
vox = ugrid.extract_points(mask)
return vox
return ugrid.extract_points(mask)


def voxelize_volume(mesh, density=None, check_surface=True):
Expand Down
3 changes: 1 addition & 2 deletions pyvista/core/utilities/geometric_sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -1307,11 +1307,10 @@ def point_dtype(self) -> str:
It must be either 'float32' or 'float64'.
"""
precision = self.GetOutputPointsPrecision()
point_dtype = {
return {
SINGLE_PRECISION: 'float32',
DOUBLE_PRECISION: 'float64',
}[precision]
return point_dtype

@point_dtype.setter
def point_dtype(self, point_dtype: str):
Expand Down
2 changes: 1 addition & 1 deletion pyvista/core/utilities/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ def wrap(
return pyvista._wrappers[key](dataset)
except KeyError:
raise TypeError(f'VTK data type ({key}) is not currently supported by pyvista.')
return
return None # pragma: no cover

# wrap meshio
if is_meshio_mesh(dataset):
Expand Down
1 change: 1 addition & 0 deletions pyvista/core/utilities/transformations.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,7 @@ def apply_transformation_to_points(transformation, points, inplace=False):
# If inplace, set the points
if inplace:
points[:] = points_2
return None
else:
# otherwise return the new points
return points_2
3 changes: 1 addition & 2 deletions pyvista/examples/examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -543,8 +543,7 @@ def _explicit_structured_load_func(dimensions=(5, 6, 7), spacing=(20, 10, 1)):
corners = np.stack((xcorn, ycorn, zcorn))
corners = corners.transpose()

grid = pyvista.ExplicitStructuredGrid(dimensions, corners)
return grid
return pyvista.ExplicitStructuredGrid(dimensions, corners)


_dataset_explicit_structured = _DatasetLoader(_explicit_structured_load_func)
Expand Down

0 comments on commit 1f3f47b

Please sign in to comment.