How do I tell PyLint “it's a variable, not a c

2019-01-22 05:58发布

问题:

I have a module-level variable in my Python 2.6 program named "_log", which PyLint complains about:

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

Having read this answer I understand why it's doing this: it thinks the variable is a constant and applies the constant regex. However, I beg to differ: I think it's a variable. How do I tell PyLint that, so it doesn't complain? How does PyLint determine whether it's a variable or a constant - does it just treat all module-level variables as constants?

回答1:

# 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


回答2:

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

[BASIC]
good-names=_log


回答3:

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.



回答4:

In newer versions of pylint this line is now

# pylint: disable=C0103

the enable message is as simple

# pylint: enable=C0103


回答5:

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!



回答6:

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


标签: python pylint