[Python-Dev] Silly pystones question

Tim Peters tim.one@home.com
Sun, 12 Aug 2001 23:46:06 -0400


[Skip Montanaro]
> In pystones.Proc0, most of the variables declared global are
> never assigned.  Was that just slavish adherence to the style of code
> from which it was adapted or was the code changed at some point in
> the past, making the global declarations superfluous?

You're a developer, Skip:  it's time you learned how to use CVS <wink>:

<http://cvs.sf.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Lib/test/pysto
ne.py>

The evidence there says it's always been this way.

> Seems to me that the only time the global keyword should be used is
> when an assignment to the variable occurs in the code and you want
> to make sure you're modifying the global name.

Well, like any other declaration, it can also have documentation value; and
sometimes you'll see every function in a module repeat the same global decl.
"just for consistency" (I guess).

> This is obviously a silly piece of code in which to question this
> technique, but I was looking at it to gauge the effects of possible
> global object access optimization.  My first assumption was that a
> variable declared global wouldn't be subject to any optimization, but
> now I realize I'd have to look for variables that were operands of
> LOAD_GLOBAL instructions but not STORE_GLOBAL instructions.

Until The Rules change, any global (or builtin) is subject to rebinding at
any time, even if there's no STORE_GLOBAL in sight.  The "danger" across
call sites is clear enough (a Python global is like a C extern), but in the
presence of threads another thread can reach into the module and rebind its
globals between any pair of byte codes (which C worms around via X3J11
refusing to say anthing at all about threads <0.9 wink>).