user3313834
user3313834

Reputation: 7827

Pylint message: Invalid constant name (invalid-name)

Pylint complains about Invalid constant name "myprint" (invalid-name) in the case of a shorthand for a logger function.

# import
from utils import get_logger
LOGFILE = '6_evaluator.log'
myprint = get_logger(LOGFILE)

def main():
    # some stuff
    myprint('log log')

if __name__ == '__main__':
    main()

Can this be done without tweaking the pylint configuration ?

If needed, here is the definition of get_logger:

import logging
import os

def get_logger(logfile):
    """ Return a logger that log on stdout and in LOGFILE"""
    if os.path.isfile('{}'.format(logfile)):
        os.remove('{}'.format(logfile))

    logging.basicConfig(filename='{}'.format(logfile), level=logging.INFO)
    logger = logging.getLogger('')
    logger.addHandler(logging.StreamHandler())
    myprint = logger.info

    myprint('log file at: {}'.format(logfile))
    myprint('Again Hello from logger')
    return myprint

Upvotes: 17

Views: 10265

Answers (2)

Asclepius
Asclepius

Reputation: 63252

Moving the definition of myprint to main() is one way to suppress the message.

Per Pylint docs for invalid-name (C0103), it would seem that a constant's name must effectively be uppercase. As such, the name MYPRINT will not generate the message.

If you append the comment as below to the line, the message should not be generated.

log = get_logger()  # pylint: disable=locally-disabled, invalid-name

Alternatively, add the following to .pylintrc for your project. This is my preferred solution.

[BASIC]
good-names=log

If you wanted an entire pattern of invalid names (and not just a single name) to be valid, you can otherwise customize const-rgx, etc. in the same section. Refer to the pylint page linked earlier.

Lastly, if your application is small and independent, you can just configure and use the root logger instead such as with logging.warn('test').

Upvotes: 20

pettinato
pettinato

Reputation: 1542

The issue is that you are defining myprint at the module level.

If you define it within main you will not get this error from pylint.

Upvotes: 2

Related Questions