Why does RE-importing after a module is used in a function throw an exception?

Viewed 46

I'm diddling python2.7 here:

import time

def foo():
    print time.time()  # EXCEPTION THROWN HERE
    import time

...which throws the exception:

UnboundLocalError: local variable 'time' referenced before assignment

If I remove the re-import:

import time

def foo():
    print time.time()  # WORKS AS EXPECTED
    #import time

...everything works as it should. It's pretty clear that, when the function is called, something about the later import affects the local variable table, from the moment execution of the function begins - NOT from the point of the inclusion:

import time

def foo():
    global time
    print time.time()  # WORKS AS EXPECTED
    import time

...weird.

This came up because an engineer was adding a call to time.time() at the top of a large method, but didn't see it imported in the middle of the function (by an engineer who is long since gone.) I'm not looking for guidance on how to solve the problem - that's pathetically obvious (and will also involve hunting down the guy who did this, providing the necessary dope slap.)

I'm curious as to the mechanism, why it's done this way, and what parts of the system I can inspect to see it all in action.

1 Answers
Related