Skip to content

Commit bc3d11b

Browse files
Activate and fix existing use-set-for-membership checks
1 parent 07a635c commit bc3d11b

20 files changed

+61
-68
lines changed

pylint/checkers/base.py

+8-8
Original file line numberDiff line numberDiff line change
@@ -2251,7 +2251,7 @@ def _check_docstring(
22512251
func.bound, astroid.Instance
22522252
):
22532253
# Strings.
2254-
if func.bound.name in ("str", "unicode", "bytes"):
2254+
if func.bound.name in {"str", "unicode", "bytes"}:
22552255
return
22562256
if node_type == "module":
22572257
message = "missing-module-docstring"
@@ -2386,7 +2386,7 @@ def _is_singleton_const(node) -> bool:
23862386

23872387
# True/False singletons have a special-cased message in case the user is
23882388
# mistakenly using == or != to check for truthiness
2389-
if singleton in (True, False):
2389+
if singleton in {True, False}:
23902390
suggestion_template = (
23912391
"{} if checking for the singleton value {}, or {} if testing for {}"
23922392
)
@@ -2440,7 +2440,7 @@ def _is_float_nan(node):
24402440
def _is_numpy_nan(node):
24412441
if isinstance(node, nodes.Attribute) and node.attrname == "NaN":
24422442
if isinstance(node.expr, nodes.Name):
2443-
return node.expr.name in ("numpy", "nmp", "np")
2443+
return node.expr.name in {"numpy", "nmp", "np"}
24442444
return False
24452445

24462446
def _is_nan(node) -> bool:
@@ -2540,16 +2540,16 @@ def visit_compare(self, node: nodes.Compare) -> None:
25402540
left = node.left
25412541
operator, right = node.ops[0]
25422542

2543-
if operator in ("==", "!="):
2543+
if operator in {"==", "!="}:
25442544
self._check_singleton_comparison(
25452545
left, right, node, checking_for_absence=operator == "!="
25462546
)
25472547

2548-
if operator in ("==", "!=", "is", "is not"):
2548+
if operator in {"==", "!=", "is", "is not"}:
25492549
self._check_nan_comparison(
2550-
left, right, node, checking_for_absence=operator in ("!=", "is not")
2550+
left, right, node, checking_for_absence=operator in {"!=", "is not"}
25512551
)
2552-
if operator in ("is", "is not"):
2552+
if operator in {"is", "is not"}:
25532553
self._check_literal_comparison(right, node)
25542554

25552555
def _check_unidiomatic_typecheck(self, node):
@@ -2567,7 +2567,7 @@ def _check_type_x_is_y(self, node, left, operator, right):
25672567
):
25682568
return
25692569

2570-
if operator in ("is", "is not") and _is_one_arg_pos_call(right):
2570+
if operator in {"is", "is not"} and _is_one_arg_pos_call(right):
25712571
right_func = utils.safe_infer(right.func)
25722572
if (
25732573
isinstance(right_func, nodes.ClassDef)

pylint/checkers/classes.py

+7-11
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@ def _definition_equivalent_to_call(definition, call):
178178

179179
def _positional_parameters(method):
180180
positional = method.args.args
181-
if method.type in ("classmethod", "method"):
181+
if method.type in {"classmethod", "method"}:
182182
positional = positional[1:]
183183
return positional
184184

@@ -1000,14 +1000,10 @@ def _check_unused_private_attributes(self, node: nodes.ClassDef) -> None:
10001000
if attribute.attrname != assign_attr.attrname:
10011001
continue
10021002

1003-
if (
1004-
assign_attr.expr.name
1005-
in [
1006-
"cls",
1007-
node.name,
1008-
]
1009-
and attribute.expr.name in ["cls", "self", node.name]
1010-
):
1003+
if assign_attr.expr.name in {
1004+
"cls",
1005+
node.name,
1006+
} and attribute.expr.name in {"cls", "self", node.name}:
10111007
# If assigned to cls or class name, can be accessed by cls/self/class name
10121008
break
10131009

@@ -1130,11 +1126,11 @@ def visit_functiondef(self, node: nodes.FunctionDef) -> None:
11301126

11311127
if node.decorators:
11321128
for decorator in node.decorators.nodes:
1133-
if isinstance(decorator, nodes.Attribute) and decorator.attrname in (
1129+
if isinstance(decorator, nodes.Attribute) and decorator.attrname in {
11341130
"getter",
11351131
"setter",
11361132
"deleter",
1137-
):
1133+
}:
11381134
# attribute affectation will call this method, not hiding it
11391135
return
11401136
if isinstance(decorator, nodes.Name):

pylint/checkers/format.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -411,9 +411,9 @@ def _check_keyword_parentheses(
411411
contains_double_parens -= 1
412412
continue
413413
# ')' can't happen after if (foo), since it would be a syntax error.
414-
if tokens[i + 1].string in (":", ")", "]", "}", "in") or tokens[
414+
if tokens[i + 1].string in {":", ")", "]", "}", "in"} or tokens[
415415
i + 1
416-
].type in (tokenize.NEWLINE, tokenize.ENDMARKER, tokenize.COMMENT):
416+
].type in {tokenize.NEWLINE, tokenize.ENDMARKER, tokenize.COMMENT}:
417417
if contains_walrus_operator and walrus_operator_depth - 1 == depth:
418418
return
419419
# The empty tuple () is always accepted.
@@ -424,7 +424,7 @@ def _check_keyword_parentheses(
424424
self.add_message(
425425
"superfluous-parens", line=line_num, args=keyword_token
426426
)
427-
elif keyword_token in ("return", "yield"):
427+
elif keyword_token in {"return", "yield"}:
428428
self.add_message(
429429
"superfluous-parens", line=line_num, args=keyword_token
430430
)
@@ -439,7 +439,7 @@ def _check_keyword_parentheses(
439439
return
440440
# 'and' and 'or' are the only boolean operators with lower precedence
441441
# than 'not', so parens are only required when they are found.
442-
if token[1] in ("and", "or"):
442+
if token[1] in {"and", "or"}:
443443
found_and_or = True
444444
# A yield inside an expression must always be in parentheses,
445445
# quit early without error.

pylint/checkers/imports.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -734,7 +734,7 @@ def _check_imports_order(self, _module_node):
734734
)
735735
import_category = isort_driver.place_module(package)
736736
node_and_package_import = (node, package)
737-
if import_category in ("FUTURE", "STDLIB"):
737+
if import_category in {"FUTURE", "STDLIB"}:
738738
std_imports.append(node_and_package_import)
739739
wrong_import = (
740740
third_party_not_ignored

pylint/checkers/refactoring/implicit_booleaness_checker.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ def _check_use_implicit_booleaness_not_comparison(
177177
continue
178178

179179
# No need to check for operator when visiting compare node
180-
if operator in ("==", "!=", ">=", ">", "<=", "<"):
180+
if operator in {"==", "!=", ">=", ">", "<=", "<"}:
181181
collection_literal = "{}"
182182
if isinstance(literal_node, nodes.List):
183183
collection_literal = "[]"

pylint/checkers/refactoring/recommendation_checker.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ def _check_use_maxsplit_arg(self, node: nodes.Call) -> None:
106106
# Check if call is split() or rsplit()
107107
if not (
108108
isinstance(node.func, nodes.Attribute)
109-
and node.func.attrname in ("split", "rsplit")
109+
and node.func.attrname in {"split", "rsplit"}
110110
and isinstance(utils.safe_infer(node.func), astroid.BoundMethod)
111111
):
112112
return

pylint/checkers/refactoring/refactoring_checker.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -833,14 +833,14 @@ def _check_consider_using_min_max_builtin(self, node: nodes.If):
833833
if right_statement_value != body_value:
834834
return
835835

836-
if operator in ("<", "<="):
836+
if operator in {"<", "<="}:
837837
reduced_to = "{target} = max({target}, {item})".format(
838838
target=target_assignation, item=body_value
839839
)
840840
self.add_message(
841841
"consider-using-max-builtin", node=node, args=(reduced_to,)
842842
)
843-
elif operator in (">", ">="):
843+
elif operator in {">", ">="}:
844844
reduced_to = "{target} = min({target}, {item})".format(
845845
target=target_assignation, item=body_value
846846
)
@@ -963,7 +963,7 @@ def _check_consider_using_generator(self, node):
963963
# remove square brackets '[]'
964964
inside_comp = node.args[0].as_string()[1:-1]
965965
call_name = node.func.name
966-
if call_name in ["any", "all"]:
966+
if call_name in {"any", "all"}:
967967
self.add_message(
968968
"use-a-generator",
969969
node=node,
@@ -1227,12 +1227,12 @@ def _find_lower_upper_bounds(comparison_node, uses):
12271227
if value is None:
12281228
continue
12291229

1230-
if operator in ("<", "<="):
1230+
if operator in {"<", "<="}:
12311231
if operand is left_operand:
12321232
uses[value]["lower_bound"].add(comparison_node)
12331233
elif operand is right_operand:
12341234
uses[value]["upper_bound"].add(comparison_node)
1235-
elif operator in (">", ">="):
1235+
elif operator in {">", ">="}:
12361236
if operand is left_operand:
12371237
uses[value]["upper_bound"].add(comparison_node)
12381238
elif operand is right_operand:
@@ -1482,7 +1482,7 @@ def _check_consider_using_with(self, node: nodes.Call):
14821482

14831483
def _check_use_list_or_dict_literal(self, node: nodes.Call) -> None:
14841484
"""Check if empty list or dict is created by using the literal [] or {}"""
1485-
if node.as_string() in ("list()", "dict()"):
1485+
if node.as_string() in {"list()", "dict()"}:
14861486
inferred = utils.safe_infer(node.func)
14871487
if isinstance(inferred, nodes.ClassDef) and not node.args:
14881488
if inferred.qname() == "builtins.list":

pylint/checkers/similar.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -916,17 +916,17 @@ def Run(argv=None):
916916
ignore_signatures = False
917917
opts, args = getopt(argv, s_opts, l_opts)
918918
for opt, val in opts:
919-
if opt in ("-d", "--duplicates"):
919+
if opt in {"-d", "--duplicates"}:
920920
min_lines = int(val)
921-
elif opt in ("-h", "--help"):
921+
elif opt in {"-h", "--help"}:
922922
usage()
923-
elif opt in ("-i", "--ignore-comments"):
923+
elif opt in {"-i", "--ignore-comments"}:
924924
ignore_comments = True
925-
elif opt in ("--ignore-docstrings",):
925+
elif opt in {"--ignore-docstrings"}:
926926
ignore_docstrings = True
927-
elif opt in ("--ignore-imports",):
927+
elif opt in {"--ignore-imports"}:
928928
ignore_imports = True
929-
elif opt in ("--ignore-signatures",):
929+
elif opt in {"--ignore-signatures"}:
930930
ignore_signatures = True
931931
if not args:
932932
usage(1)

pylint/checkers/stdlib.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -574,7 +574,7 @@ def _check_redundant_assert(self, node, infer):
574574
isinstance(infer, astroid.BoundMethod)
575575
and node.args
576576
and isinstance(node.args[0], nodes.Const)
577-
and infer.name in ["assertTrue", "assertFalse"]
577+
and infer.name in {"assertTrue", "assertFalse"}
578578
):
579579
self.add_message(
580580
"redundant-unittest-assert",

pylint/checkers/strings.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -429,9 +429,9 @@ def visit_call(self, node: nodes.Call) -> None:
429429
if (
430430
isinstance(func, astroid.BoundMethod)
431431
and isinstance(func.bound, astroid.Instance)
432-
and func.bound.name in ("str", "unicode", "bytes")
432+
and func.bound.name in {"str", "unicode", "bytes"}
433433
):
434-
if func.name in ("strip", "lstrip", "rstrip") and node.args:
434+
if func.name in {"strip", "lstrip", "rstrip"} and node.args:
435435
arg = utils.safe_infer(node.args[0])
436436
if not isinstance(arg, nodes.Const) or not isinstance(arg.value, str):
437437
return
@@ -942,11 +942,11 @@ def str_eval(token):
942942
We have to support all string literal notations:
943943
https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals
944944
"""
945-
if token[0:2].lower() in ("fr", "rf"):
945+
if token[0:2].lower() in {"fr", "rf"}:
946946
token = token[2:]
947-
elif token[0].lower() in ("r", "u", "f"):
947+
elif token[0].lower() in {"r", "u", "f"}:
948948
token = token[1:]
949-
if token[0:3] in ('"""', "'''"):
949+
if token[0:3] in {'"""', "'''"}:
950950
return token[3:-3]
951951
return token[1:-1]
952952

pylint/checkers/typecheck.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -486,7 +486,7 @@ def _emit_no_member(
486486
return False
487487
if metaclass:
488488
# Renamed in Python 3.10 to `EnumType`
489-
return metaclass.qname() in ("enum.EnumMeta", "enum.EnumType")
489+
return metaclass.qname() in {"enum.EnumMeta", "enum.EnumType"}
490490
return False
491491
if not has_known_bases(owner):
492492
return False
@@ -525,7 +525,7 @@ def _emit_no_member(
525525
and isinstance(owner.parent, nodes.ClassDef)
526526
and owner.parent.name == "EnumMeta"
527527
and owner_name == "__members__"
528-
and node.attrname in ["items", "values", "keys"]
528+
and node.attrname in {"items", "values", "keys"}
529529
):
530530
# Avoid false positive on Enum.__members__.{items(), values, keys}
531531
# See https://github.com/PyCQA/pylint/issues/4123
@@ -1560,7 +1560,7 @@ def _check_invalid_sequence_index(self, subscript: nodes.Subscript):
15601560
return None
15611561
# Instance values must be int, slice, or have an __index__ method
15621562
elif isinstance(index_type, astroid.Instance):
1563-
if index_type.pytype() in ("builtins.int", "builtins.slice"):
1563+
if index_type.pytype() in {"builtins.int", "builtins.slice"}:
15641564
return None
15651565
try:
15661566
index_type.getattr("__index__")
@@ -1603,7 +1603,7 @@ def _check_invalid_slice_index(self, node: nodes.Slice) -> None:
16031603
# Instance values must be of type int, None or an object
16041604
# with __index__
16051605
elif isinstance(index_type, astroid.Instance):
1606-
if index_type.pytype() in ("builtins.int", "builtins.NoneType"):
1606+
if index_type.pytype() in {"builtins.int", "builtins.NoneType"}:
16071607
continue
16081608

16091609
try:
@@ -1805,7 +1805,7 @@ def visit_compare(self, node: nodes.Compare) -> None:
18051805
return
18061806

18071807
op, right = node.ops[0]
1808-
if op in ["in", "not in"]:
1808+
if op in {"in", "not in"}:
18091809
self._check_membership_test(right)
18101810

18111811
@check_messages(

pylint/checkers/utils.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -730,7 +730,7 @@ def inherit_from_std_ex(node: nodes.NodeNG) -> bool:
730730
"""
731731
ancestors = node.ancestors() if hasattr(node, "ancestors") else []
732732
return any(
733-
ancestor.name in ("Exception", "BaseException")
733+
ancestor.name in {"Exception", "BaseException"}
734734
and ancestor.root().name == EXCEPTIONS_MODULE
735735
for ancestor in itertools.chain([node], ancestors)
736736
)
@@ -802,7 +802,7 @@ def is_property_setter_or_deleter(node: nodes.FunctionDef) -> bool:
802802
def _is_property_decorator(decorator: nodes.Name) -> bool:
803803
for inferred in decorator.infer():
804804
if isinstance(inferred, nodes.ClassDef):
805-
if inferred.qname() in ("builtins.property", "functools.cached_property"):
805+
if inferred.qname() in {"builtins.property", "functools.cached_property"}:
806806
return True
807807
for ancestor in inferred.ancestors():
808808
if ancestor.name == "property" and ancestor.root().name == "builtins":
@@ -1688,5 +1688,5 @@ def returns_bool(node: nodes.NodeNG) -> bool:
16881688
return (
16891689
isinstance(node, nodes.Return)
16901690
and isinstance(node.value, nodes.Const)
1691-
and node.value.value in (True, False)
1691+
and node.value.value in {True, False}
16921692
)

pylint/checkers/variables.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2131,7 +2131,7 @@ def _check_all(self, node: nodes.Module, not_consumed):
21312131
assigned = next(node.igetattr("__all__"))
21322132
if assigned is astroid.Uninferable:
21332133
return
2134-
if not assigned.pytype() in ["builtins.list", "builtins.tuple"]:
2134+
if not assigned.pytype() in {"builtins.list", "builtins.tuple"}:
21352135
line, col = assigned.tolineno, assigned.col_offset
21362136
self.add_message("invalid-all-format", line=line, col_offset=col, node=node)
21372137
return

pylint/config/option.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -52,9 +52,9 @@ def _yn_validator(opt, _, value):
5252
return bool(value)
5353
if isinstance(value, str):
5454
value = value.lower()
55-
if value in ("y", "yes", "true"):
55+
if value in {"y", "yes", "true"}:
5656
return True
57-
if value in ("n", "no", "false"):
57+
if value in {"n", "no", "false"}:
5858
return False
5959
msg = "option %s: invalid yn value %r, should be in (y, yes, true, n, no, false)"
6060
raise optparse.OptionValueError(msg % (opt, value))
@@ -164,7 +164,7 @@ def __init__(self, *opts, **attrs):
164164
self.help = optparse.SUPPRESS_HELP
165165

166166
def _check_choice(self):
167-
if self.type in ("choice", "multiple_choice"):
167+
if self.type in {"choice", "multiple_choice"}:
168168
if self.choices is None:
169169
raise optparse.OptionError(
170170
"must supply a list of choices for type 'choice'", self

pylint/config/options_provider_mixin.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def set_option(self, optname, value, action=None, optdict=None):
5656
action = optdict.get("action", "store")
5757
if action == "store":
5858
setattr(self.config, self.option_attrname(optname, optdict), value)
59-
elif action in ("store_true", "count"):
59+
elif action in {"store_true", "count"}:
6060
setattr(self.config, self.option_attrname(optname, optdict), 0)
6161
elif action == "store_false":
6262
setattr(self.config, self.option_attrname(optname, optdict), 1)

pylint/extensions/typing.py

+1-5
Original file line numberDiff line numberDiff line change
@@ -194,11 +194,7 @@ def _check_for_alternative_union_syntax(
194194
inferred = safe_infer(node)
195195
if not (
196196
isinstance(inferred, nodes.FunctionDef)
197-
and inferred.qname()
198-
in (
199-
"typing.Optional",
200-
"typing.Union",
201-
)
197+
and inferred.qname() in {"typing.Optional", "typing.Union"}
202198
or isinstance(inferred, astroid.bases.Instance)
203199
and inferred.qname() == "typing._SpecialForm"
204200
):

0 commit comments

Comments
 (0)