Saturday, June 13, 2009

Python and scope

I think this rule with scope in Python is not intuitive. Take a look at the following program:

1 x = 1
2
3 def main():
4 print x
5
6 main()

x is in scope within main(), and the program runs correctly. Now look at this program:

1 x = 1
2
3 def main():
4 print x
5 x = 1
6
7 main()

This program fails, it can't print x because the value for x has not been set before printing it in line 4.

Why? x is set in line 1, correct? True. But that x is not in scope.

By setting x=1 in the main function, we get a brand new variable called x, which is only in the main function. There are 2 variables, both named x. One for the main file script, and one for the main function. And since x has not been set in the main function, print x does not work.