fragglet ([info]fragglet) wrote,
@ 2009-05-07 12:30:00
Previous Entry  Add to memories!  Tell a Friend  Next Entry
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?



(2 comments) - (Post a new comment)


[info]lionsphil
2009-05-07 04:54 pm UTC (link)
That would blow up in your face if someone came along and added a global which name-conflicted with one in a function. This particular brain-damage is shared by PHP.

At the end of the day, though---automatic variable declaration: just say no.

(Reply to this) (Thread)

Oh Dear,
[info]ah_see_argh
2009-05-10 02:40 am UTC (link)
I was wondering today why so many adverts for "Software Engineers" request people with experience of Multi-Threaded development, or inheritance, or some such. Of course it's because there are some numpties who somehow believe that a few months of BASIC makes them a software engineer... and there are meta-numpties who employ them.

(Reply to this) (Parent)


(2 comments) - (Post a new comment)

Create an Account
Forgot your login or password?
Login w/ OpenID
English • Español • Deutsch • Русский…