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

Emit consider-using-tuple for in comparisons #4853

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ Release date: TBA
Put new features here and also in 'doc/whatsnew/2.11.rst'


* ``CodeStyleChecker``

* Emit ``consider-using-tuple`` for ``in`` comparisons when a ``list`` is used.


What's New in Pylint 2.10.1?
============================
Release date: TBA
Expand Down
4 changes: 4 additions & 0 deletions doc/whatsnew/2.11.rst
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ New checkers
Extensions
==========

* ``CodeStyleChecker``

* Emit ``consider-using-tuple`` for ``in`` comparisons when a ``list`` is used.


Other Changes
=============
4 changes: 2 additions & 2 deletions pylint/checkers/classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1000,10 +1000,10 @@ def _check_unused_private_attributes(self, node: nodes.ClassDef) -> None:
if attribute.attrname != assign_attr.attrname:
continue

if assign_attr.expr.name == "cls" and attribute.expr.name in [
if assign_attr.expr.name == "cls" and attribute.expr.name in (
"cls",
"self",
]:
):
# If assigned to cls.attrib, can be accessed by cls/self
break

Expand Down
2 changes: 1 addition & 1 deletion pylint/checkers/python3.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ def _in_iterating_context(node):
elif (
isinstance(parent, nodes.Compare)
and len(parent.ops) == 1
and parent.ops[0][0] in ["in", "not in"]
and parent.ops[0][0] in ("in", "not in")
):
return True
# Also if it's an `yield from`, that's fair
Expand Down
2 changes: 1 addition & 1 deletion pylint/checkers/refactoring/refactoring_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -966,7 +966,7 @@ def _check_consider_using_generator(self, node):
# remove square brackets '[]'
inside_comp = node.args[0].as_string()[1:-1]
call_name = node.func.name
if call_name in ["any", "all"]:
if call_name in ("any", "all"):
self.add_message(
"use-a-generator",
node=node,
Expand Down
2 changes: 1 addition & 1 deletion pylint/checkers/stdlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -566,7 +566,7 @@ def _check_redundant_assert(self, node, infer):
isinstance(infer, astroid.BoundMethod)
and node.args
and isinstance(node.args[0], nodes.Const)
and infer.name in ["assertTrue", "assertFalse"]
and infer.name in ("assertTrue", "assertFalse")
):
self.add_message(
"redundant-unittest-assert",
Expand Down
4 changes: 2 additions & 2 deletions pylint/checkers/typecheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -517,7 +517,7 @@ def _emit_no_member(node, owner, owner_name, ignored_mixins=True, ignored_none=T
and isinstance(owner.parent, nodes.ClassDef)
and owner.parent.name == "EnumMeta"
and owner_name == "__members__"
and node.attrname in ["items", "values", "keys"]
and node.attrname in ("items", "values", "keys")
):
# Avoid false positive on Enum.__members__.{items(), values, keys}
# See https://github.com/PyCQA/pylint/issues/4123
Expand Down Expand Up @@ -1778,7 +1778,7 @@ def visit_compare(self, node):
return

op, right = node.ops[0]
if op in ["in", "not in"]:
if op in ("in", "not in"):
self._check_membership_test(right)

@check_messages(
Expand Down
6 changes: 6 additions & 0 deletions pylint/extensions/code_style.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,12 @@ def visit_comprehension(self, node: nodes.Comprehension) -> None:
if isinstance(node.iter, nodes.List):
self.add_message("consider-using-tuple", node=node.iter)

@check_messages("consider-using-tuple")
def visit_compare(self, node: nodes.Compare) -> None:
for op, comparator in node.ops:
if op == "in" and isinstance(comparator, nodes.List):
self.add_message("consider-using-tuple", node=comparator)

def _check_dict_consider_namedtuple_dataclass(self, node: nodes.Dict) -> None:
"""Check if dictionary values can be replaced by Namedtuple or Dataclass."""
if not (
Expand Down
2 changes: 1 addition & 1 deletion pylint/lint/pylinter.py
Original file line number Diff line number Diff line change
Expand Up @@ -728,7 +728,7 @@ def any_fail_on_issues(self):
def disable_noerror_messages(self):
for msgcat, msgids in self.msgs_store._msgs_by_category.items():
# enable only messages with 'error' severity and above ('fatal')
if msgcat in ["E", "F"]:
if msgcat in ("E", "F"):
for msgid in msgids:
self.enable(msgid)
else:
Expand Down
2 changes: 1 addition & 1 deletion script/bump_changelog.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ def do_checks(content, next_version, version, version_type):
wn_next_version = get_whats_new(next_version)
wn_this_version = get_whats_new(version)
# There is only one field where the release date is TBA
if version_type in [VersionType.MAJOR, VersionType.MINOR]:
if version_type in (VersionType.MAJOR, VersionType.MINOR):
assert (
content.count(RELEASE_DATE_TEXT) <= 1
), f"There should be only one release date 'TBA' ({version}) {err}"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,31 @@
# Don't emit warning for sets as this is handled by builtin checker
(x for x in {1, 2, 3}) # [use-sequence-for-iteration]
[x for x in {*var, 2}] # [use-sequence-for-iteration]


# -----
# Suggest tuple for `in` comparisons
x in var
x in {1, 2, 3}
x in (1, 2, 3)
x in [1, 2, 3] # [consider-using-tuple]

if x in var:
pass
if x in {1, 2, 3}:
pass
if x in (1, 2, 3):
pass
if x in [1, 2, 3]: # [consider-using-tuple]
pass

42 if x in [1, 2, 3] else None # [consider-using-tuple]
assert x in [1, 2, 3] # [consider-using-tuple]
(x for x in var if x in [1, 2, 3]) # [consider-using-tuple]
while x in [1, 2, 3]: # [consider-using-tuple]
break

# Stacked operators, rightmost pair is evaluated first
# Doesn't make much sense in practice since `in` will only return `bool`
True == x in [1, 2, 3] # [consider-using-tuple] # noqa: E712
1 >= x in [1, 2, 3] # [consider-using-tuple] # noqa: E712
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,11 @@ consider-using-tuple:23:9::Consider using an in-place tuple instead of list
consider-using-tuple:26:12::Consider using an in-place tuple instead of list
use-sequence-for-iteration:30:12::Use a sequence type when iterating over values
use-sequence-for-iteration:31:12::Use a sequence type when iterating over values
consider-using-tuple:39:5::Consider using an in-place tuple instead of list
consider-using-tuple:47:8::Consider using an in-place tuple instead of list
consider-using-tuple:50:11::Consider using an in-place tuple instead of list
consider-using-tuple:51:12::Consider using an in-place tuple instead of list
consider-using-tuple:52:24::Consider using an in-place tuple instead of list
consider-using-tuple:53:11::Consider using an in-place tuple instead of list
consider-using-tuple:58:13::Consider using an in-place tuple instead of list
consider-using-tuple:59:10::Consider using an in-place tuple instead of list