Tuesday, May 19, 2009

Python surprises - scope of variables

Yesterday while debugging one place in some function I found one "surprise" in Python - language that I thought was designed to avoid surprises as much as possible(Principle of least astonishment).

if 1 == 1:
    print dir()
    found = True
    print dir()

print dir()
print "found:", found

Output:
['__builtins__', '__doc__', '__file__', '__name__', '__package__']
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'found']
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'found']
found: True


As you would have guessed coming from C++, here we had variable used out of its scope. But in Python variables live in special dictionaries - one is global where global variables and other stuff are stored and another one is local, for keeping local symbols inside the function. So all variables you create inside "for" loop or "if" scope will be stored in that local dictionary and will only be removed from there when Python's garbage collector decides.

That surprise cost me 30 minutes of wondering why some polygons on a map suddenly went nuts and lost their shapes :)

1 comment:

  1. thanks, was on the watchout for something like this and I was wondering if i knew it correctly in C :P

    ReplyDelete