Problem with global variables

irstas at gmail.com irstas at gmail.com
Mon Apr 2 10:59:40 EDT 2007


On Apr 2, 5:29 pm, Bjoern Schliessmann <usenet-
mail-0306.20.chr0n... at spamgourmet.com> wrote:
> Laurent Pointal wrote:
> > And so the solution to add "global foo" before using it.
>
> Didn't you read his final question?
>
> | All of a sudden, tiny() can see the global variable "foo".  Very
> | confusing!  Why is it that tiny() sometimes can, and sometimes
> | can't, see the global variable "foo"?
>
> I have no explanation for this, but I'm interested in one, too.
>
> Regards,
>
> Björn

Laurent Pointal did explain this. "foo" is considered to be a local
variable (scope limited to the function) if it's being assigned to in
a function and there's no "global foo" statement. So even the "foo"
before the actual assignment will refer to the local variable. But the
local variable hasn't been assigned yet at that point and an exception
is thrown. Yes, one could have a perfectly working function, then add
an innocent-looking assignment statement at the very end of the
function, and suddenly you'd get an exception thrown at the beginning
of the function where that variable is used - Far away from the place
where the modification was made.

Why does it work like this? Couldn't it be somehow more uniform or
less surprising?

Well, if one had to define "global foo" even when one were to just
read the variable foo, that'd be a pain in the ass. You'd have to use
"global math" to use math module in a function and "global
anotherFunction" to call anotherFunction, and so on. There's plenty of
stuff in the global scope that you don't normally assign to.

Another option would be to scrap "global" keyword and let "foo = bar"
do an assignment to the global variable if a global variable named
"foo" exists, but create (or assign) to a function local variable if
it doesn't exist. That'd work but programming would be horrible. Now
you'd have to know all the symbols that exist at the global scope,
because if you accidentally accessed a global variable instead of
local, your function would probably have undesirable side-effects.

Now, name clashes could be solved with a naming convention (which
could be enforced at the language level). It could be possible that
all accesses to global scope would have to be prefixed by some symbol
like $. E.g. "$foo = 4; foo = 6" where former assigns to global foo,
latter to local foo. That's one option that might work and be somewhat
readable.. But not a good tradeoff IMO, considering how rarely global
assignment is needed and how often global variables are read.

A remaining option is to use different operator for assignment and
initialization. So you'd have to do e.g. "a := 4; a = 7". I'm not sure
Pythonistas would prefer this either, although many other languages
choose this route (through lets or declarations typically).




More information about the Python-list mailing list