Skip to content

Commit ab63ccc

Browse files
committed
Add flake8-comprehensions
1 parent 3df9798 commit ab63ccc

24 files changed

+74
-74
lines changed

hypothesis-python/RELEASE.rst

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
RELEASE_TYPE: patch
2+
3+
This patch adds :pypi:`flake8-comprehensions` to our linter suite. There is no
4+
user-visible change - expect perhaps via some strange microbenchmarks - but
5+
certain parts of the code now have a clear and more consistent style.

hypothesis-python/src/hypothesis/_strategies.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1017,7 +1017,7 @@ def characters(
10171017
"Nothing is excluded by other arguments, so passing only "
10181018
"whitelist_characters=%(chars)r would have no effect. Also pass "
10191019
"whitelist_categories=(), or use sampled_from(%(chars)r) instead."
1020-
% dict(chars=whitelist_characters)
1020+
% {"chars": whitelist_characters}
10211021
)
10221022
blacklist_characters = blacklist_characters or ""
10231023
whitelist_characters = whitelist_characters or ""
@@ -2017,7 +2017,7 @@ def complex_numbers(
20172017
"Cannot have allow_nan=%r, min_magnitude=%r max_magnitude=%r"
20182018
% (allow_nan, min_magnitude, max_magnitude)
20192019
)
2020-
allow_kw = dict(allow_nan=allow_nan, allow_infinity=allow_infinity)
2020+
allow_kw = {"allow_nan": allow_nan, "allow_infinity": allow_infinity}
20212021

20222022
if min_magnitude is None and max_magnitude is None:
20232023
# In this simple but common case, there are no constraints on the

hypothesis-python/src/hypothesis/core.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -700,7 +700,7 @@ def run_engine(self):
700700
return
701701
if runner.interesting_examples:
702702
self.falsifying_examples = sorted(
703-
[d for d in runner.interesting_examples.values()],
703+
runner.interesting_examples.values(),
704704
key=lambda d: sort_key(d.buffer),
705705
reverse=True,
706706
)

hypothesis-python/src/hypothesis/extra/dateutil.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ def timezones():
6363
information.
6464
"""
6565
all_timezones = sorted(
66-
[tz.gettz(t) for t in zoneinfo.get_zonefile_instance().zones],
66+
(tz.gettz(t) for t in zoneinfo.get_zonefile_instance().zones),
6767
key=__zone_sort_key,
6868
)
6969
all_timezones.insert(0, tz.UTC)

hypothesis-python/src/hypothesis/extra/django/_fields.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -136,11 +136,11 @@ def _for_slug(field):
136136

137137
@register_for(dm.GenericIPAddressField)
138138
def _for_model_ip(field):
139-
return dict(
140-
ipv4=ip4_addr_strings(),
141-
ipv6=ip6_addr_strings(),
142-
both=ip4_addr_strings() | ip6_addr_strings(),
143-
)[field.protocol.lower()]
139+
return {
140+
"ipv4": ip4_addr_strings(),
141+
"ipv6": ip6_addr_strings(),
142+
"both": ip4_addr_strings() | ip6_addr_strings(),
143+
}[field.protocol.lower()]
144144

145145

146146
@register_for(df.GenericIPAddressField)

hypothesis-python/src/hypothesis/internal/charmap.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -102,9 +102,9 @@ def charmap():
102102
# and that both elements of that tuple are integers.
103103
for vs in _charmap.values():
104104
ints = list(sum(vs, ()))
105-
assert all([isinstance(x, int) for x in ints])
105+
assert all(isinstance(x, int) for x in ints)
106106
assert ints == sorted(ints)
107-
assert all([len(tup) == 2 for tup in vs])
107+
assert all(len(tup) == 2 for tup in vs)
108108

109109
assert _charmap is not None
110110
return _charmap

hypothesis-python/src/hypothesis/searchstrategy/datetime.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def __init__(self, min_value, max_value, timezones_strat):
4646
self.tz_strat = timezones_strat
4747

4848
def do_draw(self, data):
49-
result = dict()
49+
result = {}
5050
cap_low, cap_high = True, True
5151
for name in ("year", "month", "day", "hour", "minute", "second", "microsecond"):
5252
low = getattr(self.min_dt if cap_low else dt.datetime.min, name)
@@ -96,7 +96,7 @@ def __init__(self, min_value, max_value):
9696
self.max_value = max_value
9797

9898
def do_draw(self, data):
99-
result = dict()
99+
result = {}
100100
low_bound = True
101101
high_bound = True
102102
for name in ("days", "seconds", "microseconds"):

hypothesis-python/tests/cover/test_attrs_inference.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ class Inferrables(object):
7070
has_default = attr.ib(default=0)
7171
has_default_factory = attr.ib(default=attr.Factory(list))
7272
has_default_factory_takes_self = attr.ib( # uninferrable but has default
73-
default=attr.Factory(lambda _: list(), takes_self=True)
73+
default=attr.Factory(lambda _: [], takes_self=True)
7474
)
7575

7676

hypothesis-python/tests/cover/test_feature_flags.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def test_minimizes_individual_features_to_open():
4545
features = list(hrange(10))
4646

4747
flags = minimal(
48-
STRAT, lambda x: sum([x.is_enabled(i) for i in features]) < len(features)
48+
STRAT, lambda x: sum(x.is_enabled(i) for i in features) < len(features)
4949
)
5050

5151
assert all(flags.is_enabled(i) for i in features[:-1])

hypothesis-python/tests/cover/test_float_nastiness.py

+8-8
Original file line numberDiff line numberDiff line change
@@ -211,14 +211,14 @@ def test_float16_can_exclude_infinity(x):
211211
@pytest.mark.parametrize(
212212
"kwargs",
213213
[
214-
dict(min_value=10 ** 5, width=16),
215-
dict(max_value=10 ** 5, width=16),
216-
dict(min_value=10 ** 40, width=32),
217-
dict(max_value=10 ** 40, width=32),
218-
dict(min_value=10 ** 400, width=64),
219-
dict(max_value=10 ** 400, width=64),
220-
dict(min_value=10 ** 400),
221-
dict(max_value=10 ** 400),
214+
{"min_value": 10 ** 5, "width": 16},
215+
{"max_value": 10 ** 5, "width": 16},
216+
{"min_value": 10 ** 40, "width": 32},
217+
{"max_value": 10 ** 40, "width": 32},
218+
{"min_value": 10 ** 400, "width": 64},
219+
{"max_value": 10 ** 400, "width": 64},
220+
{"min_value": 10 ** 400},
221+
{"max_value": 10 ** 400},
222222
],
223223
)
224224
def test_out_of_range(kwargs):

hypothesis-python/tests/cover/test_settings.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -466,11 +466,11 @@ def test_derandomise_with_explicit_database_is_invalid():
466466
@pytest.mark.parametrize(
467467
"kwargs",
468468
[
469-
dict(max_examples=-1),
470-
dict(buffer_size=-1),
471-
dict(stateful_step_count=-1),
472-
dict(deadline=-1),
473-
dict(deadline=0),
469+
{"max_examples": -1},
470+
{"buffer_size": -1},
471+
{"stateful_step_count": -1},
472+
{"deadline": -1},
473+
{"deadline": 0},
474474
],
475475
)
476476
def test_invalid_settings_are_errors(kwargs):

hypothesis-python/tests/cover/test_simple_collections.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,10 @@ def test_can_find_unique_lists_of_non_set_order():
152152
# a consistent value. This could be 0, or it could be the PYTHONHASHSEED
153153
# value listed in a failure log from CI.
154154

155-
ls = minimal(lists(text(), unique=True), lambda x: list(set(reversed(x))) != x)
155+
ls = minimal(
156+
lists(text(), unique=True),
157+
lambda x: list(set(reversed(x))) != x, # noqa: C414 # yes, reverse inside set
158+
)
156159
assert len(set(ls)) == len(ls)
157160
assert len(ls) == 2
158161

hypothesis-python/tests/cover/test_type_lookup.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ def test_uninspectable_from_type():
222222

223223

224224
@pytest.mark.parametrize(
225-
"typ", sorted([x for x in _global_type_lookup if x.__module__ != "typing"], key=str)
225+
"typ", sorted((x for x in _global_type_lookup if x.__module__ != "typing"), key=str)
226226
)
227227
@given(data=st.data())
228228
def test_can_generate_from_all_registered_types(data, typ):

hypothesis-python/tests/nocover/test_from_type_recipe.py

+3-8
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@
2121
from hypothesis import given
2222
from hypothesis.searchstrategy.types import _global_type_lookup
2323

24+
TYPES = sorted((x for x in _global_type_lookup if x.__module__ != "typing"), key=str)
25+
2426

2527
def everything_except(excluded_types):
2628
"""Recipe copied from the docstring of ``from_type``"""
@@ -33,14 +35,7 @@ def everything_except(excluded_types):
3335

3436
@given(
3537
excluded_types=st.lists(
36-
st.sampled_from(
37-
sorted(
38-
[x for x in _global_type_lookup if x.__module__ != "typing"], key=str
39-
)
40-
),
41-
min_size=1,
42-
max_size=3,
43-
unique=True,
38+
st.sampled_from(TYPES), min_size=1, max_size=3, unique=True,
4439
).map(tuple),
4540
data=st.data(),
4641
)

hypothesis-python/tests/nocover/test_pretty_repr.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -52,11 +52,10 @@ def splat(value):
5252
return st.tuples(st.tuples(*args), st.fixed_dictionaries(kwargs)).map(splat)
5353

5454

55-
size_strategies = dict(
56-
min_size=st.integers(min_value=0, max_value=100),
57-
max_size=st.integers(min_value=0, max_value=100) | st.none(),
58-
)
59-
55+
size_strategies = {
56+
"min_size": st.integers(min_value=0, max_value=100),
57+
"max_size": st.integers(min_value=0, max_value=100) | st.none(),
58+
}
6059

6160
values = st.integers() | st.text()
6261

hypothesis-python/tests/numpy/test_argument_validation.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -313,7 +313,7 @@ def test_test_basic_indices_kwonly_emulation():
313313
nps.basic_indices((), __reserved=None).validate()
314314

315315

316-
@pytest.mark.parametrize("args", ({}, (1,), dict(num_shapes=1, __reserved=None)))
316+
@pytest.mark.parametrize("args", ({}, (1,), {"num_shapes": 1, "__reserved": None}))
317317
def test_test_mutually_broadcastable_shapes_kwonly_emulation(args):
318318
with pytest.raises(TypeError):
319319
if isinstance(args, dict):

hypothesis-python/tests/numpy/test_gen_data.py

+12-14
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ def test_minimise_array_shapes(min_dims, dim_range, min_side, side_range):
192192

193193

194194
@pytest.mark.parametrize(
195-
"kwargs", [dict(min_side=100), dict(min_dims=15), dict(min_dims=32)]
195+
"kwargs", [{"min_side": 100}, {"min_dims": 15}, {"min_dims": 32}]
196196
)
197197
def test_interesting_array_shapes_argument(kwargs):
198198
nps.array_shapes(**kwargs).example()
@@ -453,9 +453,9 @@ def test_all_inferred_scalar_strategies_roundtrip(data, dtype):
453453
@checks_deprecated_behaviour
454454
@given(st.data())
455455
def test_overflowing_integers_are_deprecated(fill, data):
456-
kw = dict(elements=st.just(300))
456+
kw = {"elements": st.just(300)}
457457
if fill:
458-
kw = dict(elements=st.nothing(), fill=kw["elements"])
458+
kw = {"elements": st.nothing(), "fill": kw["elements"]}
459459
arr = data.draw(nps.arrays(dtype="int8", shape=(1,), **kw))
460460
assert arr[0] == (300 % 256)
461461

@@ -475,9 +475,9 @@ def test_overflowing_integers_are_deprecated(fill, data):
475475
@given(data=st.data())
476476
def test_unrepresentable_elements_are_deprecated(fill, dtype, strat, data):
477477
if fill:
478-
kw = dict(elements=st.nothing(), fill=strat)
478+
kw = {"elements": st.nothing(), "fill": strat}
479479
else:
480-
kw = dict(elements=strat)
480+
kw = {"elements": strat}
481481
arr = data.draw(nps.arrays(dtype=dtype, shape=(1,), **kw))
482482
try:
483483
# This is a float or complex number, and has overflowed to infinity,
@@ -992,7 +992,7 @@ def test_mutually_broadcastable_shapes_only_singleton_is_valid(
992992
assert len(input_shapes) == num_shapes
993993
assert result == _broadcast_shapes(base_shape, *input_shapes)
994994
for shape in input_shapes:
995-
assert all([i == 1 for i in shape[-len(base_shape) :]])
995+
assert all(i == 1 for i in shape[-len(base_shape) :])
996996

997997

998998
@settings(deadline=None)
@@ -1007,11 +1007,10 @@ def test_broadcastable_shape_can_generate_arbitrary_ndims(shape, max_dims, data)
10071007
min_dims = data.draw(
10081008
st.one_of(st.none(), st.integers(0, desired_ndim)), label="min_dims"
10091009
)
1010-
args = (
1011-
dict(min_dims=min_dims) if min_dims is not None else {}
1012-
) # check default arg behavior too
1010+
# check default arg behavior too
1011+
kwargs = {"min_dims": min_dims} if min_dims is not None else {}
10131012
find_any(
1014-
nps.broadcastable_shapes(shape, min_side=0, max_dims=max_dims, **args),
1013+
nps.broadcastable_shapes(shape, min_side=0, max_dims=max_dims, **kwargs),
10151014
lambda x: len(x) == desired_ndim,
10161015
settings(max_examples=10 ** 6),
10171016
)
@@ -1035,16 +1034,15 @@ def test_mutually_broadcastable_shapes_can_generate_arbitrary_ndims(
10351034
min_dims = data.draw(
10361035
st.one_of(st.none(), st.integers(0, min(desired_ndims))), label="min_dims"
10371036
)
1038-
args = (
1039-
dict(min_dims=min_dims) if min_dims is not None else {}
1040-
) # check default arg behavior too
1037+
# check default arg behavior too
1038+
kwargs = {"min_dims": min_dims} if min_dims is not None else {}
10411039
find_any(
10421040
nps.mutually_broadcastable_shapes(
10431041
num_shapes=num_shapes,
10441042
base_shape=base_shape,
10451043
min_side=0,
10461044
max_dims=max_dims,
1047-
**args
1045+
**kwargs
10481046
),
10491047
lambda x: {len(s) for s in x.input_shapes} == set(desired_ndims),
10501048
settings(max_examples=10 ** 6),

hypothesis-python/tests/py3/test_annotations.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -87,16 +87,16 @@ def test_converter_handles_kwonly_args():
8787
def f(*, a, b=2):
8888
pass
8989

90-
out = convert_positional_arguments(f, (), dict(a=1))
91-
assert out == ((), dict(a=1, b=2))
90+
out = convert_positional_arguments(f, (), {"a": 1})
91+
assert out == ((), {"a": 1, "b": 2})
9292

9393

9494
def test_converter_notices_missing_kwonly_args():
9595
def f(*, a, b=2):
9696
pass
9797

9898
with pytest.raises(TypeError):
99-
assert convert_positional_arguments(f, (), dict())
99+
assert convert_positional_arguments(f, (), {})
100100

101101

102102
def pointless_composite(draw: None, strat: bool, nothing: list) -> int:

hypothesis-python/tests/py3/test_lookup.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -437,9 +437,9 @@ def method(self, a: int, b: int):
437437
((), {}),
438438
((1,), {}),
439439
((1, 2), {}),
440-
((), dict(a=1)),
441-
((), dict(b=2)),
442-
((), dict(a=1, b=2)),
440+
((), {"a": 1}),
441+
((), {"b": 2}),
442+
((), {"a": 1, "b": 2}),
443443
],
444444
)
445445
def test_required_args(target, args, kwargs):

hypothesis-python/tests/quality/test_integers.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -118,9 +118,7 @@ def f(data):
118118
# have power of two sizes, so it may be up to a factor of two more than
119119
# that.
120120
bits_needed = 1 + n.bit_length()
121-
actual_bits_needed = min(
122-
[s for s in WideRangeIntStrategy.sizes if s >= bits_needed]
123-
)
121+
actual_bits_needed = min(s for s in WideRangeIntStrategy.sizes if s >= bits_needed)
124122
bytes_needed = actual_bits_needed // 8
125123
# 3 extra bytes: two for the sampler, one for the capping value.
126124
assert len(v.buffer) == 3 + bytes_needed

hypothesis-python/tests/quality/test_shrink_quality.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -325,7 +325,7 @@ def test_can_find_sets_unique_by_incomplete_data():
325325
lists(tuples(integers(), integers()), unique_by=max), lambda x: len(x) >= size
326326
)
327327
assert len(ls) == size
328-
values = sorted(list(map(max, ls)))
328+
values = sorted(map(max, ls))
329329
assert values[-1] - values[0] == size - 1
330330
for u, _ in ls:
331331
assert u <= 0

requirements/tools.in

+1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ flake8
99
flake8-alfred
1010
flake8-bandit
1111
flake8-bugbear
12+
flake8-comprehensions
1213
flake8-docstrings
1314
ipython
1415
isort

requirements/tools.txt

+2-1
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,15 @@ filelock==3.0.12 # via tox
3030
flake8-alfred==1.1.1
3131
flake8-bandit==2.1.2
3232
flake8-bugbear==19.8.0
33+
flake8-comprehensions==3.1.4
3334
flake8-docstrings==1.5.0
3435
flake8-polyfill==1.0.2 # via flake8-bandit
3536
flake8==3.7.9
3637
gitdb2==2.0.6 # via gitpython
3738
gitpython==3.0.4 # via bandit
3839
idna==2.8 # via requests
3940
imagesize==1.1.0 # via sphinx
40-
importlib-metadata==0.23 # via pluggy, pytest, tox
41+
importlib-metadata==0.23 # via flake8-comprehensions, pluggy, pytest, tox
4142
ipython-genutils==0.2.0 # via traitlets
4243
ipython==7.9.0
4344
isort==4.3.21

tooling/src/hypothesistooling/projects/hypothesispython.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -201,11 +201,11 @@ def upload_distribution():
201201
# https://developer.github.com/v3/repos/releases/#create-a-release
202202
requests.post(
203203
"https://api.github.com/repos/HypothesisWorks/hypothesis/releases",
204-
json=dict(
205-
tag_name=tag_name(),
206-
name="Hypothesis for Python - version " + current_version(),
207-
body=changelog_body,
208-
),
204+
json={
205+
"tag_name": tag_name(),
206+
"name": "Hypothesis for Python - version " + current_version(),
207+
"body": changelog_body,
208+
},
209209
timeout=120, # seconds
210210
# Scoped personal access token, stored in Travis environ variable
211211
auth=("Zac-HD", os.environ["Zac_release_token"]),

0 commit comments

Comments
 (0)