[Tutor] imported module/global

Andreas Kostyrka andreas at kostyrka.org
Mon Apr 16 08:00:27 CEST 2007


* Cecilia Alm <ebbaalm at uiuc.edu> [070416 07:45]:
> OK, apologies if my terminology and wording was unfortunate and unclear.
> 
> (Setting aside for now if this is preferred practice or not) In
> regards to modifying a global mutable list/dictionary (for example
> appending to a global list), the name does not need defined within the
> local namespace, right? However, for example for a global integer
> counter, the name would need to be defined in the local name space, as
> shown by Andreas' previous example.
Naturally. But you should not confuse these two operations. Rebinding
(assigning) a name is a different beast than modifying an existing
object.

t1.py:
from t2 import x, test
test()
print x # prints [123]

t2.py:
x = []

def test():
    x.append(123)

Compare with this:

t1.py:
from t2 import x, test
test()
print x # prints 0

t2.py:
x = 0

def test():
    global x
    x = 123

And concerning your claim that adding a global is more readable for
access, I'd like to point out, that if I need to see who uses
"VarName", I usually just search for the string. If I need to see who
rebinds "VarName", I search for "global VarName" => thus
systematically adding global will make your code harder to understand
for the typical developer.

OTOH, module globals are seldom used, and usually frowned on. E.g. the
python2.5 standard lib (>200K lines, 584 py files), uses exactly 104
distinct global statements.

andreas at andi-lap:/usr/lib/python2.5> grep -r "^[ \t]*global " . | sed 's/[ \t][ \t]*/ /' | sort -u | wc -l
105
andreas at andi-lap:/usr/lib/python2.5> find . -name \*.py | xargs wc -l | tail -1
 202106 insgesamt
andreas at andi-lap:/usr/lib/python2.5> find . -name \*.py | wc -l
584

In practice I have seldom to use globals.

Andreas


More information about the Tutor mailing list