Search code examples
python-2.7datetimeglobal-variablessleep

Update Python global time variable using time.time() doesn't work


The variable created by time.time() shouldn't be immutable, right? Therefore, I should be able to change it to something else. I'm having trouble doing this, and it doesn't seem like the .sleep() method helps.

I set a variable e, to the current time. I print e. Then I update the variable e, using a function. Then I print e. The two printed values should be different, but they aren't. How do I achieve the correct update to the "global" variable e?

import time

e = time.time()
print ('e is %f') %e

time.sleep(1.12)
def uu(x):
    #time.sleep(2)
    x = time.time()

uu(e)
print ('%f') %e

No matter when I put the time delay, the two prints of e are exactly the same. However, I passed e to the function, and e is not immutable, but it doesn't change with the new assignment statement (even if there was a time delay before the call of the function [externally or internally]).

I'm expecting an output like

e is 1432940101.000643
1432940102.120643

Where the first value a second value differ by any amount.


Solution

  • This is a scope/namespace issue. e is declared Globally. Even though I pass e into the function uu, that doesn't change the globally defined value of e.

    However, if I were to put a print statement within uu then e with the scope of that function, would have a different value.