如何告诉 PyLint“它是一个变量,而不是一个常量”来停止消息 C0103?

我在 Python 2.6程序中有一个名为“ _ log”的模块级变量,PyLint 抱怨说:

C0103: Invalid name "_log" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)

读过 这个答案之后,我明白了它为什么这么做: 它认为变量是一个常量,并应用常量 regex。然而,我不敢苟同: 我认为这是一个变量。我怎么告诉 PyLint 这个,它就不会抱怨了?PyLint 如何确定它是一个变量还是一个常量——它是否仅仅将所有模块级别的变量视为常量?

44955 次浏览
# pylint: disable-msg=C0103

Put it in the scope where you want these warnings to be ignored. You can also make the above an end-of-line comment, to disable the message only for that line of code.

IIRC it is true that pylint interprets all module-level variables as being 'constants'.

newer versions of pylint will take this line instead

# pylint: disable=C0103

Seems to me a bit of refactor might help. Pylint in looking at this as a module, so it would be reasonable not to expect to see variables at this level. Conversely it doesn't complain about vars in classes or functions. The following paradigm seems quite common and solves the issue:

def main():
'''Entry point if called as an executable'''
_log = MyLog()  # . . .


if __name__ == '__main__':
main()

This has the benefit that if you have some useful classes, I can import them without running your main. The __name__ is that of the module so the "if" fails.

In newer versions of pylint this line is now

# pylint: disable=C0103

the enable message is as simple

# pylint: enable=C0103

If you disable a message locally in your file then Pylint will report another different warning!

Locally disabling invalid-name (C0103) [I:locally-disabled]

If your intention is for a clean lint run, and surely that should be the target otherwise why are you bothering, then you can disable that message and the corresponding locally-enabled message in your configuration file:

disable=locally-disabled, locally-enabled

As other answers have indicated you can disable a specific PyLint warning (such C0103) as by including the following line:

# pylint: disable=C0103

but this generates the Locally disabling invalid-name warning. Note that this secondary warning could be useful if you want to be reminded of the disabled warning. If you want to disable the warning silently without altering your config file (which would disable the warning globally) you can use:

# pylint: disable=I0011,C0103

Note that PyLint does not issue a warning that you are disabling I0011!

You can also specify a comma separated list of "good-names" that are always allowed in your pylintrc, eg:

[BASIC]
good-names=_log