Just to help any confusion for future readers, let me just explain what's happening behind the scenes here. In OP's code:
def run():
print var
if __name__ == '__main__':
var = 'yes'
run()
var
is declared at the top-level of the file and so var
automatically becomes a global variable.* Then run()
will notice that var
exists in the global scope and it'll simply print it.
This behaviour is often undesirable* so the solution is to avoid having var
be a global variable. To do that we need to declare var
inside of a function or class. One example:
def run():
print var # this line will fail, which is what we want
def main():
var = 'yes'
run()
if __name__ == '__main__':
main()
Since var
is declared inside a function, in this case main()
, var
only exists inside main()
's local scope. run()
will notice that var
doesn't exist inside its own local scope or in the global scope and it will fail.
*In Python, any variable declared at the top-level (meaning its not declared inside a function or class, it's just out in the open) is automatically considered a global variable. Global variables can be accessed from anywhere. This is typically undesirable. This is why good programmers will usually avoid writing top-level code and just put all their code in a main() function or other functions/classes.
*See why here. Or just google "python why are global variables undesirable".
main
(or anything else) and only call it inside theif
if you like.run()
andrun
can of course see all outer variables (although not change them).