Python rocks
Hendrik van Rooyen
mail at microcorp.co.za
Sun Jun 3 04:13:24 EDT 2007
"Mark Carter" <me at pr...net> wrote:
> Josiah Carlson wrote:
> > What kind of scoping did you desire?
>
> Well, I had in mind so that if you defined a function, but wanted to
> access a global var, that you didn't have to use the global keyword. Not
> much of a biggie, I guess.
You can access them without the global keyword - for "reading" .
You only need global if you are assigning to it - else you get a new function
local:
>>> x = 7
>>> def rubbish():
print x
>>> rubbish()
7
>>> def more_rubbish():
x = x+1
print x
>>> more_rubbish()
Traceback (most recent call last):
File "<pyshell#10>", line 1, in ?
more_rubbish()
File "<pyshell#9>", line 2, in more_rubbish
x = x+1
UnboundLocalError: local variable 'x' referenced before assignment
>>>def other_rubbish():
y = x+1
print y
>>> other_rubbish()
8
>>> x
7
>>> def global_rubbish():
global x
x = x + 1
print x
>>> global_rubbish()
8
>>> print x
8
>>>
- Hendrik
More information about the Python-list
mailing list