Content-Length: 1387760 | pFad | http://github.com/numpy/numpy/commit/b85d6e2c7d187b07ce11da7609d0aff87c9564ab

AB MNT: Apply ruff/Pylint rule PLR6201 · numpy/numpy@b85d6e2 · GitHub
Skip to content

Commit b85d6e2

Browse files
MNT: Apply ruff/Pylint rule PLR6201
Use a set literal when testing for membership
1 parent 0c21896 commit b85d6e2

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

70 files changed

+226
-226
lines changed

benchmarks/benchmarks/bench_ufunc_strides.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ def time_unary(self, ufunc, stride_in, stride_out, dtype):
101101

102102
class UnaryFP(_AbstractUnary):
103103
params = [[uf for uf in UFUNCS_UNARY
104-
if uf not in (np.invert, np.bitwise_count)],
104+
if uf not in {np.invert, np.bitwise_count}],
105105
[1, 4],
106106
[1, 2],
107107
['e', 'f', 'd']]

doc/neps/tools/build_index.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def nep_metadata():
5454
'(note that — here is a special, elongated dash). Got: '
5555
f' {tags["Title"]!r}')
5656

57-
if tags['Status'] in ('Accepted', 'Rejected', 'Withdrawn'):
57+
if tags['Status'] in {'Accepted', 'Rejected', 'Withdrawn'}:
5858
if 'Resolution' not in tags:
5959
raise RuntimeError(
6060
f'NEP {nr} is Accepted/Rejected/Withdrawn but '

numpy/_array_api_info.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ def default_dtypes(self, *, device=None):
171171
'indexing': numpy.int64}
172172
173173
"""
174-
if device not in ["cpu", None]:
174+
if device not in {"cpu", None}:
175175
raise ValueError(
176176
'Device not understood. Only "cpu" is allowed, but received:'
177177
f' {device}'
@@ -238,7 +238,7 @@ def dtypes(self, *, device=None, kind=None):
238238
'int64': numpy.int64}
239239
240240
"""
241-
if device not in ["cpu", None]:
241+
if device not in {"cpu", None}:
242242
raise ValueError(
243243
'Device not understood. Only "cpu" is allowed, but received:'
244244
f' {device}'

numpy/_build_utils/tempita/_tempita.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -796,7 +796,7 @@ def parse_expr(tokens, name, context=()):
796796
name=name,
797797
)
798798
return ("py", pos, expr), tokens[1:]
799-
elif expr in ("continue", "break"):
799+
elif expr in {"continue", "break"}:
800800
if "for" not in context:
801801
raise TemplateError("continue outside of for loop", position=pos, name=name)
802802
return (expr, pos), tokens[1:]
@@ -806,9 +806,9 @@ def parse_expr(tokens, name, context=()):
806806
raise TemplateError(
807807
"%s outside of an if block" % expr.split()[0], position=pos, name=name
808808
)
809-
elif expr in ("if", "elif", "for"):
809+
elif expr in {"if", "elif", "for"}:
810810
raise TemplateError("%s with no expression" % expr, position=pos, name=name)
811-
elif expr in ("endif", "endfor", "enddef"):
811+
elif expr in {"endif", "endfor", "enddef"}:
812812
raise TemplateError("Unexpected %s" % expr, position=pos, name=name)
813813
elif expr.startswith("for "):
814814
return parse_for(tokens, name, context)
@@ -1038,7 +1038,7 @@ def get_token(pos=False):
10381038
elif (
10391039
not nest_count
10401040
and tok_type == tokenize.OP
1041-
and tok_string in ("(", "[", "{")
1041+
and tok_string in {"(", "[", "{"}
10421042
):
10431043
nest_type = tok_string
10441044
nest_count = 1

numpy/_core/_dtype.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ def _scalar_str(dtype, short):
150150

151151
elif np.issubdtype(dtype, np.number):
152152
# Short repr with endianness, like '<f8'
153-
if short or dtype.byteorder not in ('=', '|'):
153+
if short or dtype.byteorder not in {'=', '|'}:
154154
return "'%s%c%d'" % (byteorder, dtype.kind, dtype.itemsize)
155155

156156
# Longer repr, like 'float64'
@@ -361,7 +361,7 @@ def _name_get(dtype):
361361
name += f"{dtype.itemsize * 8}"
362362

363363
# append metadata to datetimes
364-
if dtype.type in (np.datetime64, np.timedelta64):
364+
if dtype.type in {np.datetime64, np.timedelta64}:
365365
name += _datetime_metadata_str(dtype)
366366

367367
return name

numpy/_core/_internal.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def _makenames_list(adict, align):
3030

3131
for fname, obj in adict.items():
3232
n = len(obj)
33-
if not isinstance(obj, tuple) or n not in (2, 3):
33+
if not isinstance(obj, tuple) or n not in {2, 3}:
3434
raise ValueError("entry not a 2- or 3- tuple")
3535
if n > 2 and obj[2] == fname:
3636
continue
@@ -187,7 +187,7 @@ def _commastring(astr):
187187
(order1, order2))
188188
order = order1
189189

190-
if order in ('|', '=', _nbo):
190+
if order in {'|', '=', _nbo}:
191191
order = ''
192192
dtype = order + dtype
193193
if repeats == '':
@@ -694,14 +694,14 @@ def __dtype_from_pep3118(stream, is_subdtype):
694694
shape = tuple(map(int, shape.split(',')))
695695

696696
# Byte order
697-
if stream.next in ('@', '=', '<', '>', '^', '!'):
697+
if stream.next in {'@', '=', '<', '>', '^', '!'}:
698698
byteorder = stream.advance(1)
699699
if byteorder == '!':
700700
byteorder = '>'
701701
stream.byteorder = byteorder
702702

703703
# Byte order characters also control native vs. standard type sizes
704-
if stream.byteorder in ('@', '^'):
704+
if stream.byteorder in {'@', '^'}:
705705
type_map = _pep3118_native_map
706706
type_map_chars = _pep3118_native_typechars
707707
else:

numpy/_core/_type_aliases.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@
9797
"complex": set(), "others": set()}
9898

9999
for type_info in typeinfo.values():
100-
if type_info.kind in ["M", "m"]: # exclude timedelta and datetime
100+
if type_info.kind in {"M", "m"}: # exclude timedelta and datetime
101101
continue
102102

103103
concrete_type = type_info.type

numpy/_core/arrayprint.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ def _make_options_dict(precision=None, threshold=None, edgeitems=None,
6666
raise ValueError("floatmode option must be one of " +
6767
", ".join(f'"{m}"' for m in modes))
6868

69-
if sign not in [None, '-', '+', ' ']:
69+
if sign not in {None, '-', '+', ' '}:
7070
raise ValueError("sign option must be one of ' ', '+', or '-'")
7171

7272
if legacy is False:
@@ -1048,7 +1048,7 @@ def fillFormat(self, data):
10481048
self.exp_size = -1
10491049
self.unique = unique
10501050

1051-
if self.floatmode in ['fixed', 'maxprec_equal']:
1051+
if self.floatmode in {'fixed', 'maxprec_equal'}:
10521052
self.precision = self.min_digits = self.pad_right
10531053
self.trim = 'k'
10541054
else:

numpy/_core/einsumfunc.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -912,7 +912,7 @@ def einsum_path(*operands, optimize='greedy', einsum_call=False):
912912
# For broadcasting cases we always want the largest dim size
913913
if dimension_dict[char] == 1:
914914
dimension_dict[char] = dim
915-
elif dim not in (1, dimension_dict[char]):
915+
elif dim not in {1, dimension_dict[char]}:
916916
raise ValueError("Size of label '%s' for operand %d (%d) "
917917
"does not match previous terms (%d)."
918918
% (char, tnum, dimension_dict[char], dim))
@@ -944,7 +944,7 @@ def einsum_path(*operands, optimize='greedy', einsum_call=False):
944944
path = path_type[1:]
945945
elif (
946946
(path_type is False)
947-
or (len(input_list) in [1, 2])
947+
or (len(input_list) in {1, 2})
948948
or (indices == output_set)
949949
):
950950
# Nothing to be optimized, leave it to einsum

numpy/_core/memmap.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -250,7 +250,7 @@ def __new__(subtype, filename, dtype=uint8, mode='r+', offset=0,
250250
size = bytes // _dbytes
251251
shape = (size,)
252252
else:
253-
if type(shape) not in (tuple, list):
253+
if type(shape) not in {tuple, list}:
254254
try:
255255
shape = [operator.index(shape)]
256256
except TypeError:
@@ -262,7 +262,7 @@ def __new__(subtype, filename, dtype=uint8, mode='r+', offset=0,
262262

263263
bytes = int(offset + size * _dbytes)
264264

265-
if mode in ('w+', 'r+'):
265+
if mode in {'w+', 'r+'}:
266266
# gh-27723
267267
# if bytes == 0, we write out 1 byte to allow empty memmap.
268268
bytes = max(bytes, 1)

numpy/_core/numeric.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1426,7 +1426,7 @@ def normalize_axis_tuple(axis, ndim, argname=None, allow_duplicate=False):
14261426
normalize_axis_index : normalizing a single scalar axis
14271427
"""
14281428
# Optimization to speed-up the most common cases.
1429-
if type(axis) not in (tuple, list):
1429+
if type(axis) not in {tuple, list}:
14301430
try:
14311431
axis = [operator.index(axis)]
14321432
except TypeError:
@@ -1657,7 +1657,7 @@ def cross2d(x, y):
16571657
b = moveaxis(b, axisb, -1)
16581658
msg = ("incompatible dimensions for cross product\n"
16591659
"(dimension must be 2 or 3)")
1660-
if a.shape[-1] not in (2, 3) or b.shape[-1] not in (2, 3):
1660+
if a.shape[-1] not in {2, 3} or b.shape[-1] not in {2, 3}:
16611661
raise ValueError(msg)
16621662
if a.shape[-1] == 2 or b.shape[-1] == 2:
16631663
# Deprecated in NumPy 2.0, 2023-09-26

numpy/_core/records.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ def _setfieldnames(self, names, titles):
148148
attribute """
149149

150150
if names:
151-
if type(names) in [list, tuple]:
151+
if type(names) in {list, tuple}:
152152
pass
153153
elif isinstance(names, str):
154154
names = names.split(',')
@@ -213,7 +213,7 @@ def __str__(self):
213213
return super().__str__()
214214

215215
def __getattribute__(self, attr):
216-
if attr in ('setfield', 'getfield', 'dtype'):
216+
if attr in {'setfield', 'getfield', 'dtype'}:
217217
return nt.void.__getattribute__(self, attr)
218218
try:
219219
return nt.void.__getattribute__(self, attr)
@@ -238,7 +238,7 @@ def __getattribute__(self, attr):
238238
"attribute '%s'" % attr)
239239

240240
def __setattr__(self, attr, val):
241-
if attr in ('setfield', 'getfield', 'dtype'):
241+
if attr in {'setfield', 'getfield', 'dtype'}:
242242
raise AttributeError("Cannot set '%s' attribute" % attr)
243243
fielddict = nt.void.__getattribute__(self, 'dtype').fields
244244
res = fielddict.get(attr, None)
@@ -820,7 +820,7 @@ def fromstring(datastring, dtype=None, shape=None, offset=0, formats=None,
820820
# NumPy 1.19.0, 2020-01-01
821821
shape = _deprecate_shape_0_as_None(shape)
822822

823-
if shape in (None, -1):
823+
if shape in {None, -1}:
824824
shape = (len(datastring) - offset) // itemsize
825825

826826
_array = recarray(shape, descr, buf=datastring, offset=offset)

numpy/_core/tests/_natype.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import numpy as np
1010

1111
def _create_binary_propagating_op(name, is_divmod=False):
12-
is_cmp = name.strip("_") in ["eq", "ne", "le", "lt", "ge", "gt"]
12+
is_cmp = name.strip("_") in {"eq", "ne", "le", "lt", "ge", "gt"}
1313

1414
def method(self, other):
1515
if (
@@ -38,11 +38,11 @@ def method(self, other):
3838
return pd_NA
3939

4040
elif isinstance(other, np.datetime64):
41-
if name in ["__sub__", "__rsub__"]:
41+
if name in {"__sub__", "__rsub__"}:
4242
return pd_NA
4343

4444
elif isinstance(other, np.timedelta64):
45-
if name in ["__sub__", "__rsub__", "__add__", "__radd__"]:
45+
if name in {"__sub__", "__rsub__", "__add__", "__radd__"}:
4646
return pd_NA
4747

4848
return NotImplemented

numpy/_core/tests/test_arraymethod.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def test_class_getitem(self, cls: type[np.ndarray]) -> None:
7878
@pytest.mark.parametrize("arg_len", range(4))
7979
def test_subscript_tup(self, cls: type[np.ndarray], arg_len: int) -> None:
8080
arg_tup = (Any,) * arg_len
81-
if arg_len in (1, 2):
81+
if arg_len in {1, 2}:
8282
assert cls[arg_tup]
8383
else:
8484
match = f"Too {'few' if arg_len == 0 else 'many'} arguments"

numpy/_core/tests/test_getlimits.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ def test_known_types():
156156
with np.errstate(all='ignore'):
157157
ld_ma = _discovered_machar(np.longdouble)
158158
bytes = np.dtype(np.longdouble).itemsize
159-
if (ld_ma.it, ld_ma.maxexp) == (63, 16384) and bytes in (12, 16):
159+
if (ld_ma.it, ld_ma.maxexp) == (63, 16384) and bytes in {12, 16}:
160160
# 80-bit extended precision
161161
assert_ma_equal(ld_ma, _float_ma[80])
162162
elif (ld_ma.it, ld_ma.maxexp) == (112, 16384) and bytes == 16:
@@ -171,7 +171,7 @@ def test_subnormal_warning():
171171
bytes = np.dtype(np.longdouble).itemsize
172172
with warnings.catch_warnings(record=True) as w:
173173
warnings.simplefilter('always')
174-
if (ld_ma.it, ld_ma.maxexp) == (63, 16384) and bytes in (12, 16):
174+
if (ld_ma.it, ld_ma.maxexp) == (63, 16384) and bytes in {12, 16}:
175175
# 80-bit extended precision
176176
ld_ma.smallest_subnormal
177177
assert len(w) == 0

numpy/_core/tests/test_longdouble.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def test_array_and_stringlike_roundtrip(strtype):
5858
"""
5959
o = 1 + LD_INFO.eps
6060

61-
if strtype in (np.bytes_, bytes):
61+
if strtype in {np.bytes_, bytes}:
6262
o_str = strtype(str(o).encode("ascii"))
6363
else:
6464
o_str = strtype(str(o))

numpy/_core/tests/test_multiarray.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1113,7 +1113,7 @@ def __init__(self):
11131113
pass
11141114

11151115
def __getitem__(self, ind):
1116-
if ind in [0, 1]:
1116+
if ind in {0, 1}:
11171117
return ind
11181118
else:
11191119
raise IndexError
@@ -1994,7 +1994,7 @@ def test_prod(self):
19941994
np.float32, np.float64, np.complex64, np.complex128]:
19951995
a = np.array(ba, ctype)
19961996
a2 = np.array(ba2, ctype)
1997-
if ctype in ['1', 'b']:
1997+
if ctype in {'1', 'b'}:
19981998
assert_raises(ArithmeticError, a.prod)
19991999
assert_raises(ArithmeticError, a2.prod, axis=1)
20002000
else:

numpy/_core/tests/test_nep50_promotions.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -113,15 +113,15 @@ def test_weak_promotion_scalar_path(op):
113113
# Integer path:
114114
res = op(np.uint8(3), 5)
115115
assert res == op(3, 5)
116-
assert res.dtype in (np.uint8, bool)
116+
assert res.dtype in {np.uint8, bool}
117117

118118
with pytest.raises(OverflowError):
119119
op(np.uint8(3), 1000)
120120

121121
# Float path:
122122
res = op(np.float32(3), 5.)
123123
assert res == op(3., 5.)
124-
assert res.dtype in (np.float32, bool)
124+
assert res.dtype in {np.float32, bool}
125125

126126

127127
def test_nep50_complex_promotion():

numpy/_core/tests/test_numeric.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3286,7 +3286,7 @@ def check_function(self, func, fill_value=None):
32863286
if isinstance(dtype, np.dtype):
32873287
assert_equal(arr.dtype, dtype)
32883288
elif isinstance(dtype, type(np.dtype)):
3289-
if dtype in (np.dtypes.StrDType, np.dtypes.BytesDType):
3289+
if dtype in {np.dtypes.StrDType, np.dtypes.BytesDType}:
32903290
dtype_str = np.dtype(dtype.type).str.replace('0', '1')
32913291
assert_equal(arr.dtype, np.dtype(dtype_str))
32923292
else:

numpy/_core/tests/test_numerictypes.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,9 +82,9 @@ def normalize_descr(descr):
8282
for item in descr:
8383
dtype = item[1]
8484
if isinstance(dtype, str):
85-
if dtype[0] not in ['|', '<', '>']:
85+
if dtype[0] not in {'|', '<', '>'}:
8686
onebyte = dtype[1:] == "1"
87-
if onebyte or dtype[0] in ['S', 'V', 'b']:
87+
if onebyte or dtype[0] in {'S', 'V', 'b'}:
8888
dtype = "|" + dtype
8989
else:
9090
dtype = byteorder + dtype

numpy/_core/tests/test_regression.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -674,7 +674,7 @@ def test_recarray_fields(self):
674674
np.rec.array([(1, 2), (3, 4)]),
675675
np.rec.fromarrays([(1, 2), (3, 4)], "i4,i4"),
676676
np.rec.fromarrays([(1, 2), (3, 4)])]:
677-
assert_(a.dtype in [dt0, dt1])
677+
assert_(a.dtype in {dt0, dt1})
678678

679679
def test_random_shuffle(self):
680680
# Ticket #374

numpy/_core/tests/test_scalar_methods.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ def test_abc_complexfloating(self) -> None:
156156
@pytest.mark.parametrize("arg_len", range(4))
157157
def test_abc_complexfloating_subscript_tuple(self, arg_len: int) -> None:
158158
arg_tup = (Any,) * arg_len
159-
if arg_len in (1, 2):
159+
if arg_len in {1, 2}:
160160
assert np.complexfloating[arg_tup]
161161
else:
162162
match = f"Too {'few' if arg_len == 0 else 'many'} arguments"

numpy/_core/tests/test_scalarmath.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ def check_ufunc_scalar_equivalence(op, arr1, arr2):
9090
comp_ops = {operator.ge, operator.gt, operator.le, operator.lt}
9191
if op in comp_ops and (np.isnan(scalar1) or np.isnan(scalar2)):
9292
pytest.xfail("complex comp ufuncs use sort-order, scalars do not.")
93-
if op == operator.pow and arr2.item() in [-1, 0, 0.5, 1, 2]:
93+
if op == operator.pow and arr2.item() in {-1, 0, 0.5, 1, 2}:
9494
# array**scalar special case can have different result dtype
9595
# (Other powers may have issues also, but are not hit here.)
9696
# TODO: It would be nice to resolve this issue.
@@ -945,7 +945,7 @@ def test_longdouble_with_arrlike(sctype, op):
945945
def test_longdouble_operators_with_large_int(sctype, op):
946946
# (See `test_longdouble_operators_with_obj` for why longdouble is special)
947947
# NEP 50 means that the result is clearly a (c)longdouble here:
948-
if sctype == np.clongdouble and op in [operator.mod, operator.floordiv]:
948+
if sctype == np.clongdouble and op in {operator.mod, operator.floordiv}:
949949
# The above operators are not support for complex though...
950950
with pytest.raises(TypeError):
951951
op(sctype(3), 2**64)

0 commit comments

Comments
 (0)








ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: http://github.com/numpy/numpy/commit/b85d6e2c7d187b07ce11da7609d0aff87c9564ab

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy