Skip to content
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

Add linters to deltametrics: flake8-bugbear #188

Merged
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ repos:
hooks:
- id: flake8
additional_dependencies:
# - flake8-bugbear
- flake8-bugbear
- flake8-comprehensions
- flake8-simplify
exclude: ^docs/source/pyplots/guides/.*$
Expand Down
9 changes: 5 additions & 4 deletions deltametrics/cube.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class BaseCube(abc.ABC):

"""

def __init__(self, data, read=[], varset=None, dimensions=None):
def __init__(self, data, read=(), varset=None, dimensions=None):
"""Initialize the BaseCube.

Parameters
Expand Down Expand Up @@ -579,7 +579,8 @@ def show_plan(self, *args, **kwargs):
"alternatives. To quickly show a planform slice of a cube, you "
"can use `quick_show()` with a similar API. The `show_planform` "
"method implements more features, but requires instantiating a "
"`Planform` object first. Passing arguments to `quick_show`."
"`Planform` object first. Passing arguments to `quick_show`.",
stacklevel=2,
)
# pass `t` arg to `idx` for legacy
if "t" in kwargs.keys():
Expand Down Expand Up @@ -643,7 +644,7 @@ class DataCube(BaseCube):
"""

def __init__(
self, data, read=[], varset=None, stratigraphy_from=None, dimensions=None
self, data, read=(), varset=None, stratigraphy_from=None, dimensions=None
):
"""Initialize the BaseCube.

Expand Down Expand Up @@ -888,7 +889,7 @@ def from_DataCube(
def __init__(
self,
data,
read=[],
read=(),
varset=None,
stratigraphy_from=None,
sigma_dist=None,
Expand Down
13 changes: 8 additions & 5 deletions deltametrics/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ def connect(self):
# open the dataset
_dataset = xr.open_dataset(self.data_path, engine=_engine)
except Exception as e:
raise TypeError(f"File format out of scope for DeltaMetrics: {e}")
raise TypeError(f"File format out of scope for DeltaMetrics: {e}") from e

# try to find if coordinates have been preconfigured
_coords_list = list(_dataset.coords)
Expand All @@ -246,6 +246,7 @@ def connect(self):
"with DeltaMetrics. This warning may be replaced "
"with an Error in a future version.",
UserWarning,
stacklevel=2,
)
else:
# coordinates were not found and are not being set
Expand All @@ -270,7 +271,9 @@ def connect(self):
self.meta = _meta
except OSError:
warnings.warn(
"No associated metadata was found in the given data file.", UserWarning
"No associated metadata was found in the given data file.",
UserWarning,
stacklevel=2,
)
self.meta = None

Expand Down Expand Up @@ -381,7 +384,7 @@ def get_known_coords(self, dimensions):
# get the coordinates and dimensions from the data
self.dims = under.dims
self.coords = [under.coords[dim].data for dim in self.dims]
self.dimensions = dict(zip(self.dims, self.coords))
self.dimensions = dict(zip(self.dims, self.coords, strict=True))
# otherwise, check for the arguments passed
elif not (dimensions is None):
# if dimensions was passed, it must be a dictionary
Expand All @@ -395,7 +398,7 @@ def get_known_coords(self, dimensions):
raise ValueError("`dimensions` must contain three dimensions!")
# use the dimensions keys as dims and the vals as coords
# note, we check the size against the underlying a we go
for i, (k, v) in enumerate(dimensions.items()):
for i, k in enumerate(dimensions):
if not (len(dimensions[k]) == under_shp[i]):
raise ValueError(
"Shape of `dimensions` at position {} was {}, "
Expand All @@ -415,7 +418,7 @@ def get_known_coords(self, dimensions):
self.coords = coords

self.known_coords = self.dims
self.dimensions = dict(zip(self.dims, self.coords))
self.dimensions = dict(zip(self.dims, self.coords, strict=True))

def connect(self, *args, **kwargs):
"""Connect to the data file.
Expand Down
9 changes: 4 additions & 5 deletions deltametrics/mask.py
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,8 @@ def _check_deprecated_is_mask(self, is_mask):
DeprecationWarning(
"The `is_mask` argument is deprecated. "
"It does not have any functionality."
)
),
stacklevel=2,
)

def _check_deprecated_3d_input(self, args_0_shape):
Expand Down Expand Up @@ -2107,13 +2108,11 @@ def _compute_mask(self, *args, **kwargs):
from rivamap.singularity_index import applyMMSI as MMSI
from rivamap.singularity_index import SingularityIndexFilters as SF
from rivamap.delineate import extractCenterlines as eCL
except ImportError:
except ImportError as err:
raise ImportError(
"You must install the optional dependency: rivamap, to "
"use the centerline extraction method."
)
except Exception as e:
raise e
) from err

# pop the kwargs
self.minScale = kwargs.pop("minScale", 1.5)
Expand Down
8 changes: 4 additions & 4 deletions deltametrics/mobility.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,14 +137,14 @@ def check_inputs(chmap, basevalues=None, basevalues_idx=None, window=None,
basevalues = [np.argmin(
np.abs(out_maps['chmap'].time.data - i))
for i in baselist]
except Exception:
raise TypeError('basevalues was not a list or list-able obj.')
except Exception as err:
raise TypeError('basevalues was not a list or list-able obj.') from err

if (basevalues_idx is not None):
try:
basevalues_idx = list(basevalues_idx)
except Exception:
raise TypeError('basevalues_idx was not a list or list-able obj.')
except Exception as err:
raise TypeError('basevalues_idx was not a list or list-able obj.') from err

if (basevalues is not None) and (basevalues_idx is not None):
raise Warning(
Expand Down
15 changes: 8 additions & 7 deletions deltametrics/plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@
"`Planform` object. To change the name of "
"a Planform, you must set the attribute "
"directly with `plan._name = 'name'`."
)
),
stacklevel=2,
)
# do nothing

Expand Down Expand Up @@ -1052,11 +1053,11 @@
elif isinstance(self.cube, BaseCube):
try:
self._max_disk = self.cube.meta["N0"].data
except Exception:
except Exception as err:

Check warning on line 1056 in deltametrics/plan.py

View check run for this annotation

Codecov / codecov/patch

deltametrics/plan.py#L1056

Added line #L1056 was not covered by tests
raise TypeError(
"Data cube does not contain metadata, you must "
"specify the inlet size."
)
) from err
else:
raise TypeError(
"Something went wrong. Check second input argument for " "inlet width."
Expand Down Expand Up @@ -1322,7 +1323,7 @@
return rough


def compute_shoreline_length(shore_mask, origin=[0, 0], return_line=False):
def compute_shoreline_length(shore_mask, origin=(0, 0), return_line=False):
"""Compute the length of a shoreline from a mask of the shoreline.

Algorithm attempts to determine the sorted coordinates of the shoreline
Expand Down Expand Up @@ -1553,7 +1554,7 @@
return length


def compute_shoreline_distance(shore_mask, origin=[0, 0], return_distances=False):
def compute_shoreline_distance(shore_mask, origin=(0, 0), return_distances=False):
"""Compute mean and stddev distance from the delta apex to the shoreline.

Algorithm computes the mean distance from the delta apex/origin to all
Expand Down Expand Up @@ -1895,7 +1896,7 @@
test_set_points = land_points
else:
raise ValueError(
f"Invalid option '{test_set}' for `test_set` parameter was supplied."
f"Invalid option {test_set!r} for `test_set` parameter was supplied."
)

# Find convex hull
Expand Down Expand Up @@ -1928,7 +1929,7 @@
outside_hull_value = 0
else:
raise ValueError(
f"Invalid option '{query_set}' for `query_set` parameter was supplied."
f"Invalid option {query_set!r} for `query_set` parameter was supplied."
)

# Compute opening angle
Expand Down
5 changes: 3 additions & 2 deletions deltametrics/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -1088,7 +1088,7 @@ def _fill_steps(where, x=1, y=1, y0=0, **kwargs):
Collection of `Rectangle` `Patch` objects.
"""
pl = []
for i, pp in enumerate(np.argwhere(where[1:]).flatten()):
for _, pp in enumerate(np.argwhere(where[1:]).flatten()):
_r = ptch.Rectangle((pp, y0), x, y, **kwargs)
pl.append(_r)
return coll.PatchCollection(pl, match_original=True)
Expand Down Expand Up @@ -1399,7 +1399,7 @@ def aerial_view(
datum=0,
ax=None,
ticks=False,
colorbar_kw={},
colorbar_kw=None,
return_im=False,
**kwargs,
):
Expand Down Expand Up @@ -1457,6 +1457,7 @@ def aerial_view(
>>> fig, ax = plt.subplots()
>>> _ = aerial_view(elevation_data, ax=ax)
"""
colorbar_kw = {} if colorbar_kw is None else colorbar_kw
if not ax:
fig, ax = plt.subplots()

Expand Down
1 change: 1 addition & 0 deletions deltametrics/sample_data/cube.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,6 @@ def rcm8():
"Access is maintained here for backwards compatability, "
"but will be removed in a future release.",
DeprecationWarning,
stacklevel=2,
)
return moved_rcm8()
40 changes: 29 additions & 11 deletions deltametrics/section.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,8 @@ def name(self, var):
"`Section` object. To change the name of "
"a Section, you must set the attribute "
"directly with `section._name = 'name'`."
)
),
stacklevel=2,
)
# do nothing

Expand Down Expand Up @@ -735,7 +736,7 @@ def show_trace(self, *args, ax=None, autoscale=False, **kwargs):
lims = [ax.get_xlim(), ax.get_ylim()]

# add the trace
ax.plot(_x, _y, label=_label, *args, **kwargs)
ax.plot(_x, _y, *args, label=_label, **kwargs)

# if autscale is false, reset the axes
if not autoscale:
Expand Down Expand Up @@ -967,7 +968,8 @@ def __init__(
"in a future release. Please use `distance_idx` and "
"`length` to continue to specify cell indices, or "
"use `distance` and `length` to specify "
"coordinate values."
"coordinate values.",
stacklevel=2,
)
if direction == "strike":
distance_idx = y
Expand Down Expand Up @@ -1207,7 +1209,10 @@ def _compute_section_coords(self):
@property
def y(self):
"""Deprecated. Use :obj:`distance_idx`."""
warnings.warn("`.y` is a deprecated attribute. Use `.distance_idx` instead.")
warnings.warn(
"`.y` is a deprecated attribute. Use `.distance_idx` instead.",
stacklevel=2,
)
return self._distance_idx

@property
Expand All @@ -1216,7 +1221,10 @@ def x(self):

Start and end indices of section.
"""
warnings.warn("`.x` is a deprecated attribute. Use `.length_idx` instead.")
warnings.warn(
"`.x` is a deprecated attribute. Use `.length_idx` instead.",
stacklevel=2,
)
return self._length_idx


Expand Down Expand Up @@ -1418,7 +1426,10 @@ def _compute_section_coords(self):
@property
def y(self):
"""Deprecated. Use :obj:`length_idx`."""
warnings.warn("`.y` is a deprecated attribute. Use `.length_idx` instead.")
warnings.warn(
"`.y` is a deprecated attribute. Use `.length_idx` instead.",
stacklevel=2,
)
return self._length_idx

@property
Expand All @@ -1427,7 +1438,10 @@ def x(self):

Start and end indices of section.
"""
warnings.warn("`.x` is a deprecated attribute. Use `.distance_idx` instead.")
warnings.warn(
"`.x` is a deprecated attribute. Use `.distance_idx` instead.",
stacklevel=2,
)
return self._distance_idx


Expand Down Expand Up @@ -1602,8 +1616,10 @@ def _compute_section_coords(self):
# try and guess the value (should issue a warning?)
# if no field called 'eta'?? this will fail.
warnings.warn(
"Trying to guess origin distance from dim1==0. "
"This is unlikely to work for data not generated from pyDeltaRCM."
"Trying to guess origin distance from dim1==0."
" This is unlikely to work for data not generated from"
" pyDeltaRCM.",
stacklevel=2,
)
land_width = np.minimum(
guess_land_width_from_land(
Expand Down Expand Up @@ -1852,8 +1868,10 @@ def _compute_section_coords(self):
# try and guess the value (should issue a warning?)
# if no field called 'eta'?? this will fail.
warnings.warn(
"Trying to guess origin distance from dim1==0. "
"This is unlikely to work for data not generated from pyDeltaRCM."
"Trying to guess origin distance from dim1==0."
" This is unlikely to work for data not generated from"
" pyDeltaRCM.",
stacklevel=2,
)
land_width = np.minimum(
guess_land_width_from_land(
Expand Down
8 changes: 6 additions & 2 deletions deltametrics/strat.py
Original file line number Diff line number Diff line change
Expand Up @@ -1062,8 +1062,12 @@ def _determine_strat_coordinates(elev, z=None, dz=None, nz=None):
# if nothing is supplied
if (dz is None) and (z is None) and (nz is None):
warnings.warn(
UserWarning('No specification for stratigraphy spacing '
'was supplied. Default is to use `dz=0.1`'))
UserWarning(
"No specification for stratigraphy spacing"
" was supplied. Default is to use `dz=0.1`"
),
stacklevel=2,
)
# set the default option when nothing is supplied
dz = 0.1

Expand Down
6 changes: 3 additions & 3 deletions deltametrics/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
try:
return func(*args, **kwargs)
except AttributeError as e:
raise NoStratigraphyError(e)
raise NoStratigraphyError(e) from e

Check warning on line 72 in deltametrics/utils.py

View check run for this annotation

Codecov / codecov/patch

deltametrics/utils.py#L72

Added line #L72 was not covered by tests
return decorator


Expand Down Expand Up @@ -110,7 +110,7 @@
raise TypeError('Checklist must be of type `list`,'
'but was type: %s' % type(checklist))

for c, check in enumerate(checklist):
for _, check in enumerate(checklist):

Check warning on line 113 in deltametrics/utils.py

View check run for this annotation

Codecov / codecov/patch

deltametrics/utils.py#L113

Added line #L113 was not covered by tests
has = getattr(self, check, None)
if has is None:
att_dict[check] = False
Expand All @@ -119,7 +119,7 @@

log_list = list(att_dict.values())
log_form = [value for string, value in
zip(log_list, att_dict.keys()) if not string]
zip(log_list, att_dict.keys(), strict=True) if not string]
if not all(log_list):
raise RuntimeError('Required attribute(s) not assigned: '
+ str(log_form))
Expand Down
Loading
Loading