Following Python Lazy Logging Formatting, but pylint is still showing (logging-not-lazy) messages

Viewed 660

I'm logging some info messages and wanted to make sure I was following the PEP standards. Pylint says that this line:

        LOG.info('Directories have been made in /home/bushbak2/projects/'+
                 'system_file_audit/%s/', manu)

Is not following the lazy logging format of python. Could it be because the line carries over?

This is the message I get from pylint:

auto_audit.py:157:8: W1201: Use lazy % formatting in logging functions (logging-not-lazy)

Why does pylint still raise this message? Am I not appropriately following the PEP standard?

Cheers,

Brendan

2 Answers

The problem with the + between the two strings is that adds an add operation that must be evaluated in runtime before calling LOG.debug.

This can be a performance problem if you have to evaluate this line too often even if the debug logging flag is not set for your program.

This is the abstract syntax tree for logging.debug("this is " + "a test %s", 123):

logging.debug("this is " + "a test %s", 123)

As you can see, the first argument of the function call always has an add operation.

On the other hand, if we use logging.debug("this is " "a test %s", 123) (with whitespace instead of a + sign). The python compiler produces this other AST:

logging.debug("this is " "a test %s", 123)

What happens with f-strings? A lot of people (including me) is in love with python f-strings. If we pass an f-string, the result is similar to the one with the plus sign.

The AST for logging.debug("this is a test {123}") shows python must perform a string operation before the function call: logging.debug("this is a test {123}

Your problem comes from the + in your expression. Pylint sees it as a string concatenation and thus, recommends you to do this concatenation lazily.

You can fix it by removing the +:

LOG.info('Directories have been made in /home/bushbak2/projects/'
                 'system_file_audit/%s/', manu)
Related