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

Enable flake8 simplify #1617

Merged
merged 6 commits into from
Dec 21, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions ci/linting_requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ flake8-mutable==1.2.0
flake8-pep3101==1.3.0
flake8-print==4.0.0
flake8-quotes==3.2.0
flake8-simplify==0.11.0
pep8-naming==0.11.1

flake8-rst-docstrings==0.0.14
Expand Down
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ rst-directives = plot
docstring-convention = numpy
exclude = docs build src/metpy/io/metar_parser.py
select = A B C D E F H I M Q RST S T W B902
ignore = F405 W503 RST902
ignore = F405 W503 RST902 SIM106
per-file-ignores = examples/*.py: D T003 T001
tutorials/*.py: D T003 T001
tutorials/xarray_tutorial.py: D RST304
Expand Down
5 changes: 2 additions & 3 deletions src/metpy/calc/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
* heat index
* windchill
"""
import contextlib
from itertools import product
import warnings

Expand Down Expand Up @@ -1182,10 +1183,8 @@ def _check_radians(value, max_radians=2 * np.pi):
Input value

"""
try:
with contextlib.suppress(AttributeError):
value = value.to('radians').m
except AttributeError:
pass
if np.any(np.greater(np.abs(value), max_radians)):
warnings.warn('Input over {} radians. '
'Ensure proper units are given.'.format(np.nanmax(max_radians)))
Expand Down
9 changes: 3 additions & 6 deletions src/metpy/calc/thermo.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Contains a collection of thermodynamic calculations."""
import contextlib
import warnings

import numpy as np
Expand Down Expand Up @@ -1550,10 +1551,8 @@ def mixing_ratio_from_specific_humidity(specific_humidity):
mixing_ratio, specific_humidity_from_mixing_ratio

"""
try:
with contextlib.suppress(AttributeError):
specific_humidity = specific_humidity.to('dimensionless')
except AttributeError:
pass
return specific_humidity / (1 - specific_humidity)


Expand Down Expand Up @@ -1587,10 +1586,8 @@ def specific_humidity_from_mixing_ratio(mixing_ratio):
mixing_ratio, mixing_ratio_from_specific_humidity

"""
try:
with contextlib.suppress(AttributeError):
mixing_ratio = mixing_ratio.to('dimensionless')
except AttributeError:
pass
return mixing_ratio / (1 + mixing_ratio)


Expand Down
5 changes: 2 additions & 3 deletions src/metpy/io/_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import bz2
from collections import namedtuple
import contextlib
import gzip
from io import BytesIO
import logging
Expand Down Expand Up @@ -35,10 +36,8 @@ def open_as_needed(filename, mode='rb'):
filename = BytesIO(lead + filename.read())

# If the leading bytes match one of the signatures, pass into the appropriate class.
try:
with contextlib.suppress(AttributeError):
lead = lead.encode('ascii')
except AttributeError:
pass
if lead.startswith(b'\x1f\x8b'):
filename = gzip.GzipFile(fileobj=filename)
elif lead.startswith(b'BZh'):
Expand Down
50 changes: 19 additions & 31 deletions src/metpy/io/nexrad.py
Original file line number Diff line number Diff line change
Expand Up @@ -452,31 +452,27 @@ def _decode_msg5(self, msg_hdr):
def _decode_msg13(self, msg_hdr):
data = self._buffer_segment(msg_hdr)
if data:
data = list(Struct('>{:d}h'.format(len(data) // 2)).unpack(data))
bmap = {}
date, time, num_el = data[:3]
bmap['datetime'] = nexrad_to_datetime(date, time)
date, time, num_el, *data = Struct('>{:d}h'.format(len(data) // 2)).unpack(data)
self.clutter_filter_bypass_map = {'datetime': nexrad_to_datetime(date, time),
'data': []}

offset = 3
bmap['data'] = []
num_az = 360
chunk_size = 32
bit_conv = Bits(16)
for e in range(num_el):
offset = e * num_az * chunk_size
seg_num = data[offset]
offset += 1
if seg_num != (e + 1):
log.warning('Message 13 segments out of sync -- read {} but on {}'.format(
seg_num, e + 1))

az_data = []
for _ in range(360):
for _ in range(num_az):
gates = []
for _ in range(32):
gates.extend(bit_conv(data[offset]))
offset += 1
for i in range(1, chunk_size + 1):
gates.extend(bit_conv(data[offset + i]))
az_data.append(gates)
bmap['data'].append(az_data)

self.clutter_filter_bypass_map = bmap
self.clutter_filter_bypass_map['data'].append(az_data)

if offset != len(data):
log.warning('Message 13 left data -- Used: %d Avail: %d', offset, len(data))
Expand All @@ -489,28 +485,20 @@ def _decode_msg15(self, msg_hdr):
# will be returned concatenated when this is the case
data = self._buffer_segment(msg_hdr)
if data:
data = list(Struct('>{:d}h'.format(len(data) // 2)).unpack(data))
cmap = {}
date, time, num_el = data[:3]
cmap['datetime'] = nexrad_to_datetime(date, time)
date, time, num_el, *data = Struct('>{:d}h'.format(len(data) // 2)).unpack(data)
self.clutter_filter_map = {'datetime': nexrad_to_datetime(date, time), 'data': []}

offset = 3
cmap['data'] = []
offset = 0
for _ in range(num_el):
az_data = []
for _ in range(360):
num_rng = data[offset]
offset += 1

codes = data[offset:2 * num_rng + offset:2]
offset += 1

ends = data[offset:2 * num_rng + offset:2]
offset += 2 * num_rng - 1
codes = data[offset + 1:offset + 1 + 2 * num_rng:2]
ends = data[offset + 2:offset + 2 + 2 * num_rng:2]
az_data.append(list(zip(ends, codes)))
cmap['data'].append(az_data)
offset += 2 * num_rng + 1
self.clutter_filter_map['data'].append(az_data)

self.clutter_filter_map = cmap
if offset != len(data):
log.warning('Message 15 left data -- Used: %d Avail: %d', offset, len(data))

Expand Down Expand Up @@ -2234,7 +2222,7 @@ def _unpack_packet_cell_trend(self, code, in_sym_block):
scale = 1
vals = self._read_trends()
if code in (1, 2):
ret[f'{key} Limited'] = [True if v > 700 else False for v in vals]
ret[f'{key} Limited'] = [bool(v > 700) for v in vals]
vals = [v - 1000 if v > 700 else v for v in vals]
ret[key] = [v * scale for v in vals]

Expand Down Expand Up @@ -2421,4 +2409,4 @@ def is_precip_mode(vcp_num):
True if the VCP corresponds to precipitation mode, False otherwise

"""
return not vcp_num // 10 == 3
return vcp_num // 10 != 3
5 changes: 2 additions & 3 deletions src/metpy/plots/declarative.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# SPDX-License-Identifier: BSD-3-Clause
"""Declarative plotting tools."""

import contextlib
from datetime import datetime, timedelta

import matplotlib.pyplot as plt
Expand Down Expand Up @@ -544,10 +545,8 @@ def refresh(self, _):
self.figure.canvas.draw()

# Flush out interactive events--only ok on Agg for newer matplotlib
try:
with contextlib.suppress(NotImplementedError):
self.figure.canvas.flush_events()
except NotImplementedError:
pass

def draw(self):
"""Draw the collection of panels."""
Expand Down
27 changes: 9 additions & 18 deletions src/metpy/xarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

See Also: :doc:`xarray with MetPy Tutorial </tutorials/xarray_tutorial>`.
"""
import contextlib
import functools
from inspect import signature
import logging
Expand Down Expand Up @@ -435,17 +436,9 @@ def longitude(self):

def coordinates_identical(self, other):
"""Return whether or not the coordinates of other match this DataArray's."""
# If the number of coordinates do not match, we know they can't match.
if len(self._data_array.coords) != len(other.coords):
return False

# If same length, iterate over all of them and check
for coord_name, coord_var in self._data_array.coords.items():
if coord_name not in other.coords or not other[coord_name].identical(coord_var):
return False

# Otherwise, they match.
return True
return (len(self._data_array.coords) == len(other.coords)
and all(coord_name in other.coords and other[coord_name].identical(coord_var)
for coord_name, coord_var in self._data_array.coords.items()))

@property
def time_deltas(self):
Expand Down Expand Up @@ -1033,13 +1026,13 @@ def check_axis(var, *axes):
# - _CoordinateAxisType (from THREDDS)
# - axis (CF option)
# - positive (CF standard for non-pressure vertical coordinate)
for criterion in ('standard_name', '_CoordinateAxisType', 'axis', 'positive'):
if (var.attrs.get(criterion, 'absent') in
coordinate_criteria[criterion].get(axis, set())):
return True
if any(var.attrs.get(criterion, 'absent')
in coordinate_criteria[criterion].get(axis, set())
for criterion in ('standard_name', '_CoordinateAxisType', 'axis', 'positive')):
return True

# Check for units, either by dimensionality or name
try:
with contextlib.suppress(UndefinedUnitError):
if (axis in coordinate_criteria['units'] and (
(
coordinate_criteria['units'][axis]['match'] == 'dimensionality'
Expand All @@ -1052,8 +1045,6 @@ def check_axis(var, *axes):
in coordinate_criteria['units'][axis]['units']
))):
return True
except UndefinedUnitError:
pass

# Check if name matches regular expression (non-CF failsafe)
if re.match(coordinate_criteria['regular_expression'][axis], var.name.lower()):
Expand Down
2 changes: 1 addition & 1 deletion tests/io/test_gini.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ def test_unidata_composite():
assert datetime(2018, 3, 9, 22, 25) == f.prod_desc.datetime

# Check data value
assert 66 == f.data[2160, 2130]
assert f.data[2160, 2130] == 66


def test_percent_normal():
Expand Down
5 changes: 2 additions & 3 deletions tests/plots/test_cartopy_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Test the cartopy utilities."""
import contextlib

import matplotlib
import matplotlib.pyplot as plt
import pytest

try:
with contextlib.suppress(ImportError):
from metpy.plots import USCOUNTIES, USSTATES
except ImportError:
pass # No CartoPy
from metpy.plots.cartopy_utils import import_cartopy
# Fixture to make sure we have the right backend
from metpy.testing import set_agg_backend # noqa: F401, I202
Expand Down