variable scoping problem

Alexander Schmolck a.schmolck at
Fri Apr 25 22:55:03 CEST 2003

Tung Wai Yip <tungwaiyip at> writes:

> Bingo. The 'global' keyword solved my problem. All I'm trying to do is
> to have a global variable to shared value so that one function can
> read the value saved by a previous function.
> For people with C background Python's way is rather different. It
> threats a name differently when it is used for read only versus it is
> written to. I understand your example. But I'm not sure which problem
> is worst, to threat a name differently depends on usage or to
> unintentional overwritten a global variable. 

The answer really has to be: the second one.

I think after brief consideration there can be little doubt: python's
semantics are not really likely to cause any problems *once* you understood
them[1]. If you want to change a global, you just explicitly say so (this has
the nice side effect that it also makes the code easier to read) -- simple[2].

Even if you accidently omit the global statement (not that likely, once you
know about it), the error should become obvious pretty immediately in most
cases (as in your example; in other cases pychecker is likely to find the
problem in static analysis).

But just think what would happen if assigning to a name that also happens to
exist in global scope just silently assigned to that global variable: you
would no longer know what the scope of variable is by just looking at the
function it occurs in! The net-effect would be pretty disastrous: you would be
forced to resort to idiotic naming schemes like "g_x" for "x in global scope"
and "l_x" for "local variable x" to minimize the chance of accidently
overwriting some other function/module/variable.

> C's way has its problem but at least I'm very used to it. The most
> unambigous way is to force people to declare variable first (but I guess
> this would be unpythonic :).

Yes, one could force users to declare local variables instead, but I guess
this would percuss further than one might think (consider how similar classes
and modules currently work, for example).


[1] In respect to this question of alternatives.

[2] The explicitness of a global statement also provides a convenient
    opportunity for second (third and fourth) thoughts (should I *really* be
    using a global here?).

More information about the Python-list mailing list