"Unused import warning" and pylint

Retsam picture Retsam · Aug 14, 2012 · Viewed 40.2k times · Source

So I'm working on a project in Python and trying to keep it up to standards with pylint and just generally . So, I have a source file, (We'll just call it a.py)

#a.py
import loggingsetup

def foo():
   log.info("This is a log message")

But, I want to control what the logging looks like, so in loggingsetup I have something like:

#loggingsetup.py
import logging

logging.root.setLevel(logging.DEBUG)

consoleOut = logging.StreamHandler()
consoleOut.setLevel(logging.INFO)  
consoleOut.setFormatter(logging.Formatter("\t"+logging.BASIC_FORMAT))
logging.root.addHandler(consoleOut)

#etc

Now, this seems to work alright. I suppose as a preliminary question I should ask if this is the right way to go about this, or if there's a different way of structuring my code that would be preferable.

But my main question is that when I run pylint on a.py I get a warning like "unused import - import loggingsetup", since I'm not actually calling any methods or functions from loggingsetup.

I could do something like redefine the body of loggingsetup as a function and call it, but it seems silly and error-prone (I'd have to worry about calling it twice if I did import loggingsetup from somewhere else, and if I understand how python handles imports, that's not an issue with my current setup).

I could obviously just tell pylint to ignore the warning, but I thought I'd ask here first to make sure that this isn't actually something that I should handle differently.

Answer

sthenault picture sthenault · Aug 20, 2012

In such cases, you can still explicitly tell pylint that this unused import in intended:

import loggingsetup # pylint: disable=unused-import

Notice the instruction is on the same line as the import so W0611 is only disabled for this line, and not for all the block below.