检测内置重定义(False = True)

pet*_*etr 3 python

在代码审查期间,我偶然发现了一个有趣的问题.由于Python中的所有内容都非常动态,因此可以执行以下操作:

False = True
if False:
    print "Yes please!"
Run Code Online (Sandbox Code Playgroud)

哪个行为正确并打印出来Yes please!.在理解这种行为背后的原理的同时,是否有任何自动代码检查器可以检测到这种行为?

我总是可以在检查的"假"的存在locals()globals()其他方式达到相同的效果或过多.虽然这可能与传统软件开发无关,但有时在数据分析管道等中会出现类似于他的错误.

dan*_*ano 6

对于它的价值,pylint会检测到这一点,以及任何内置的重新定义:

dan@dantop:~$ pylint h.py

No config file found, using default configuration
************* Module h
W:  1,0: Redefining built-in 'False'
Run Code Online (Sandbox Code Playgroud)

h.py:

False = True
Run Code Online (Sandbox Code Playgroud)