2

I was stumped by a situation where the python interpreter complained about a local variable foo being referenced before assignment, even though I had clearly imported the foo package and never re-assigned it.

Consider the following code:

import foo.bar
def qux():
    if(foo.bar.fred()):
        import foo.baz
        print(foo.baz.waldo())
qux()

This raises an UnboundLocalError at the line with if(foo.bar.fred()):.

This problem seems to have specific considerations that differ from most UnboundLocalError situations, and I couldn't find this specific situation posted on stack overflow or any other site.

Why does the above code raise an exception?

martineau
  • 119,623
  • 25
  • 170
  • 301
cowlinator
  • 7,195
  • 6
  • 41
  • 61

1 Answers1

2

It turns out that this exception is raised because of an implicit (hidden) re-assignment. When foo.baz is imported within the local scope of the function, it re-assigns foo to be a local variable, as opposed to a global one.

cowlinator
  • 7,195
  • 6
  • 41
  • 61