The issue at hand is best illustrated with this minimal example containing 3 scripts:
foo.py
global_val = [0]
bar.py
from foo import global_val
def work(val=global_val[0])
print("global_val: ", global_val[0])
print("val: ", val)
main.py
from bar import work
import foo
if __name__ == '__main__':
foo.global_val[0] = 1
work()
What I expect the output to be:
global_val: 1
val: 1
Actual output:
global_val: 1
val: 0
I don't understand why the default argument for val
in bar.py
isn't 1
. I'm confused because I clearly update global_val
before calling work()
, but for some reason the old value is still used as the default function argument.
It seems that the default argument is somehow pre-computed when global_val
is imported in bar.py
. Isn't Python code supposed to be dynamically compiled at run-time?
I'm using Python 3.6, if that helps.