VSCode 是说在 python 中使用 change using += 1 的变量应该是常量。这个对吗?

VSCode is saying variables which use change using += 1 in python should be constants. Is this correct?

下面是我的代码的一个极其简化的版本:

foo = 0
bar = 0
baz = 0
while True:
    answer = input('Type an input here: ')
    print('And do something with it here.')
    if answer == 'okay':
        foo += 1
    else:
        bar += 1
    baz += 1
    print(foo, bar, baz)

当我保存这个时,VSCode 给我一个警告说:

Constant name "foo" doesn't conform to UPPER_CASE naming style

Constant name "foo" doesn't conform to UPPER_CASE naming style

Constant name "foo" doesn't conform to UPPER_CASE naming style

我的问题是“+= 1”是否影响变量是否应该是常量?我认为“+= 1”会导致变量在变量变化时不是常量,但 VSCode 告诉我不是这样。

我复现了这个问题:

原因:根据official pylint documentation的描述,出现这个警告的原因是Pylint默认的常量命名风格是大写的:

"Naming style matching correct constant names.
Default: UPPER_CASE"

因此,针对“foo = 0bar = 0baz = 0”和“foo += 1 bar += 1 baz += 1 检查 Pylint 的警告",Pylint 没有给出警告,Pylint 将它们作为变量检查。

解决方法:使用默认的大写名称:FOO,BAR,BAZ。