3

For the following code

"""Test pylint on undefined variable"""
import random


def main():
    """Use undefined variable"""

    if random.randint(0, 10) == 6:
        thing = "hi"
    print(thing)


if __name__ == '__main__':
    main()

PyCharm correctly reports the problem.

enter image description here

pylint (2.0.0, Python 3.6.6) however does not recognize it:

Your code has been rated at 10.00/10 (previous run: 10.00/10, +0.00)

But I would like it to find it, in order to let my CI fail in these cases.

So in fact I have two questions:

  • Is there an option for pylint to enable so that it can find this kindf of error?
  • What linting is PyCharm using by default? (I always thought it's pylint under the hood.)
4

1 回答 1

4

是否有启用 pylint 的选项以便它可以找到这种错误?

Pylint 目前无法检测条件或控制流块中可能未定义的变量。Pylint 的未来版本可能能够识别这些类型的错误。在您提出问题时,有一个未解决的问题需要添加对识别控制流块内可能的未定义变量的支持,例如您的示例。

Pylint 确实可以识别在使用之前明确未定义的变量,如本例所示

print(x)
x = "Hello, world"

或者这个

print(y)
if random.randint(0,10) == 3:
    y = "ok"

PyCharm 默认使用什么 linting?(我一直认为这是引擎盖下的pylint。)

PyCharm 默认使用自己的内部检查库。PyCharm 是用 Java 实现的,它的检查库也是如此。

可以将 Pylint 与 PyCharm 一起使用,但它不是内置的,也不是默认使用的。此处显示了将 Pylint 配置为外部工具的解决方案,并且还有一个PyCharm 的 Pylint 插件可用。

于 2018-10-11T19:10:06.783 回答