VPfB VPfB - 4 months ago 9
Python Question

import logging.handlers breaks my program. Why?

While debugging a problem I have simplified the program in question to just few lines, but I still do not understand what's wrong. Could you please help?

import logging

def setup():
logging.warning("start")
import logging.handlers

setup()


The code above produces an exception:


logging.warning("start")

UnboundLocalError: local variable 'logging' referenced before assignment


and pylint complains:


W: 5, 4: Redefining name 'logging' from outer scope (line 1)
(redefined-outer-name)


This modification seems to help, but I do not know why:

import logging.handlers as lh


Please note that the exception is thrown BEFORE the second import statement is executed. I'm confused.

Answer

The logging.warning function will try to reference the variable from local scope first in setup() function, which is from import logging.handlers, and it finds it to be declared after the line you're using it.

Try changing it to:

import logging

def setup():
    global logging
    logging.warning("start")
    import logging.handlers

setup()