Skip to content
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: 4 additions & 1 deletion doc/whatsnew/2/2.15/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,17 @@ Summary -- Release highlights
New checkers
============


Removed checkers
================


Extensions
==========

* ``NoDictSubscriptChecker``

* Added optional extension ``no-dict-subscript`` to emit messages when the ``[]`` operator is used
to access a dictionary value.

False positives fixed
=====================
Expand Down
31 changes: 31 additions & 0 deletions pylint/extensions/dictionary_subscript.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt

"""Check for dictionary read-access via subscript."""

from astroid import Assign, Dict, nodes

from pylint.checkers import BaseChecker, utils
from pylint.lint import PyLinter


class NoDictSubscriptChecker(BaseChecker):
name = "no-dict-subscript"
msgs = {
"R5701": (
"Using dict operator [], consider using get() instead",
"dict-subscript",
"Used to warn when subscripting a dictionary instead of using the get() function",
),
}

def visit_subscript(self, node: nodes.Subscript) -> None:
if isinstance(utils.safe_infer(node.value), Dict) and not isinstance(
node.parent, Assign
):
self.add_message("dict-subscript", node=node)


def register(linter: PyLinter) -> None:
linter.register_checker(NoDictSubscriptChecker(linter))
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
"""Checks the use of dictionary subscripts"""

mydict = {"foo": 3}

print(mydict["foo"])
print(mydict.get("foo"))

mydict["foo"] = 4
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[MAIN]
load-plugins=pylint.extensions.dictionary_subscript,
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
dict-subscript:5:6:5:19::"Using dict operator [], consider using get() instead":UNDEFINED