Search code examples
pythonglobal-variableswarningspylint

Pylint - "Using the global statement"


I'm trying to work on my current python program being very conscious of pylint warnings, so while I realize I can simply turn off the warning, I want to be sure that there is not a more desirable solution before I do.

My current section of the code is my logging code. I have a function init() that sets up handlers and attaches them to the root logger, and a function set_console_level(level) that sets the level at which console messages are reported (DEBUG, INFO, etc..):

_CONSOLE_OUT = NONE

def init():
    """Set up the error handlers for the root logger"""
    console_out = logging.StreamHandler()
    console_out.setLevel(logging.INFO)  #Show info messages for now
    #...
    logging.root.addHandler(console_out)
    global _CONSOLE_OUT
    _CONSOLE_OUT = console_out

    #Rest of function sets up more handlers similarly
init()

def set_console_level(level):
    """Change the level at which console messages are printed"""
    assert __CONSOLE_OUT is not None #Set in init
    _CONSOLE_OUT.setLevel(level) 

As far as I could tell from my reading, this is the way to do this. The line global _CONSOLE_OUT is needed in order to write to the module-level variable. However, when I run pylint on this file I get the warning W: 15,4:init: Using the global statement. Is there a way to avoid this warning? A better way to approach this problem?

(Please don't say global _CONSOLE_OUT #pylint: disable=W**** without giving justification)


Solution

  • You could create it at import time:

    _console_out = ConsoleHandler()
    

    where ConsoleHandler is a factory function or your class that create and setup the handler.