Search code examples
pythonpylint

pylint plugin to warn of specific function use?


I want to have a pylint (or possibly mypy?) plugin to warn if a specific function is used. More to the point, I want to warn when a dictionary is accessed using the brackets operator instead of the get method:

mydict = { "foo": 3 }

# warning: direct dictionary access
mydict["bar"]

# no warning:
mydict.get("bar", None)

With the official docs, I managed to figure out that I have to implement a checker that overrides visit_subscript. However, inside visit_subscript, I don't have access to the type of the left-hand side, so I cannot determine if a Dict is being accessed or, say, a List, and I don't want warnings for those.

Is there a way to get the inferred type (if available) for the subscript in pylint? Or is there an alternative way to write such a plugin?


Solution

  • You have access to node, and node.value points to what is being subscripted. You can check directly if it's an instance of nodes.Dict to catch dict literals. For other types like nodes.Name or nodes.Call, you can use utils.safe_infer() to try to see if the inferred value is a dictionary. See a model in TypeChecker.visit_subscript().