7 May 2009 fraggle   » (Journeyer)

Python's braindamaged scoping rules

Python distinguishes between local and global variables from assignment statements. If a variable is assigned within a function, that variable is treated as a local variable. This means that you cannot do this:

my_var = None

def set_my_var():
    my_var = "hello world"

set_my_var()
print my_var

As my_var is assigned within the function, it is treated as a local variable that is separate to the global variable with the same name. Instead, you have to explicitly tell the compiler that you want to assign the global variable, like this:
my_var = None

def set_my_var():
    global my_var
    my_var = "hello world"

set_my_var()
print my_var

This all strikes me as rather brain-damaged. If assignments are used to detect the declaration of a variable, is it really so difficult to just examine the surrounding context to see if there is already a variable with the same name?

Syndicated 2009-05-07 11:37:54 from fragglet

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!