question on global variables
Mark McEahern
marklists at mceahern.com
Thu Oct 10 00:44:06 EDT 2002
> Somewhat new to Python here.....
>
> I want to change/use a value throughout my program - what I would normally
> refer to as a "global" variable.
>
> I see that there is a "global" command - and I assume its use would be
> global var_name. This I have coded (works) but I am unable to use
> it "global name var_name is not defined".
Consider the following example. It should make you retch:
***
#!/usr/bin/env python
global i
i = 1
def foo():
global i
i += 1
def bar():
global i
i += 1
foo()
bar()
print i
***
Why should it make you retch? Because there's no reason whatsoever for me
to use global--foo and bar would be much clearer if they operated on input
and returned as output whatever they need to communicate to their callers:
***
#!/usr/bin/env python
def foo(i):
return i + 1
def bar(i):
return i + 1
i = 1
i = foo(i)
i = bar(i)
print i
***
In other words--why let the fact that Python has a global statement fool you
into thinking you've found a problem for which it's the only much less the
best hammer?
Cheers,
// mark
-
More information about the Python-list
mailing list