Thursday, August 4, 2011

Just to really beat it in...

Ok, here are some simple examples to drive the point home.

First is a script that has a variable assigned and a function called can see this variable.



The output of this script is:

Here is a variable I can see: 42
Here is an outside variable as seen from a function: 42

Ok, this makes sense. All well and good.

Here is a script that has a variable assigned, and a function called can see it BUT when it tries to modify it I get an error.



The output:

Here is a variable I can see: 42
Traceback (most recent call last):
File "scopetest2.py", line 10, in
afunction()
File "scopetest2.py", line 4, in afunction
print "Here is an outside variable as seen from a function: %d" % im_outside
UnboundLocalError: local variable 'im_outside' referenced before assignment

If, however, I simply first inside the function state "global im_outside" it becomes allowed to modify the variable.

Alright, let us see a C example:



Output is:

Here is a variable I can see: 42
Here is an outside variable as seen from a function 42

And altering the function to modify the variable:



And I get the result I wanted:

Here is a variable I can see: 42
Here is an outside variable as seen from a function 42
But now I'm going to modify it
And here it is: 27

I am certain I understand how scope works in C. It's pretty straightforward and a lot of the difficulty with understanding passing values/references to functions is a consequence of that simple straightforwardness. I think what this means is that I don't understand scope in Python. I just think if a function can "see" a variable it should also be able to modify that variable. Look, I get it that maybe having the "global" description happen elsewhere is a good idea because then you can let SOME functions modify the var but not others, but man is it not intuitive.

No comments:

Post a Comment