I was looking at the following code:
def f():
print(x)
if __name__ == '__main__':
x = [1,2,3]
f()
which to my amazement works. I would have expected that NOT to work because I would have expected needing x
to be defined BEFORE the function definition of f
(otherwise, how does f
know what x
refers to?). So I expected the following to be the only version that should have worked:
x = [1,2,3]
def f():
print(x)
if __name__ == '__main__':
#x = [1,2,3]
f()
though I am obviously wrong. Why? What part of how Python is supposed to work did I get wrong?
Note as coding practice I'd never use globals. They are dangerous and unclear. I'd personally always pass variables to functions (or something that is more clear and safe like that). This was just out of curiosity.