473,700 Members | 2,497 Online

# Global surprise

Hello,

It must be simple but it seems I misunderstand scopes in Python... :(

Could someone out there please explain to me why this is printed?
2 {0: 1, 1: 1}
2 {}

Thanks.
N.

---- test.py ----

g = 0
di = {}

def test():
global g
di[g] = 1
g += 1

test()
test()

print g, di
Jul 18 '05 #1
3 1173
"Nick" <no****@nnn.com > wrote in message
news:co******** **@namru.matavn et.hu...
Hello,

It must be simple but it seems I misunderstand scopes in Python... :(

Could someone out there please explain to me why this is printed?
2 {0: 1, 1: 1}
2 {}

Thanks.
N.

---- test.py ----

g = 0
di = {}

def test():
global g
di[g] = 1
g += 1

test()
test()

print g, di

There is no variable di defined in the test() scope. Therefore, references
to di use the di defined in the next outer scope, the module di.

The interactive mode of Python can be very helpful.

\$ python
Python 2.1 (#15, May 4 2004, 21:22:34) [MSC 32 bit (Intel)] on win32
g = 0
di = {}
def test(): .... global g
.... di[g] = 1
.... g += 1
.... g 0 di {} test <function test at 0083844C> test()
g 1 di {0: 1} test()
g 2 di {1: 1, 0: 1} print g, di

2 {1: 1, 0: 1}
Jul 18 '05 #2
Nick a écrit :
Hello,

It must be simple but it seems I misunderstand scopes in Python... :(

Could someone out there please explain to me why this is printed?
2 {0: 1, 1: 1}
2 {}

Thanks.
N.

---- test.py ----

g = 0
di = {}

def test():
global g
di[g] = 1
g += 1

test()
test()

print g, di

Because di is a global variable, modified by the test() function (which

Try this :
g = 0
di = {}

def test():
global g
di = {g : 1}
g += 1

Here you create a local di variable, and bind a new dict to it, so it
doesnt look for another di variable in the enclosing (here the global)
scope.

Keep in mind that modifying the state of an object (your code) is not
the same thing as binding an object to a variable (my code).

HTH
Bruno
Jul 18 '05 #3
On Wed, 24 Nov 2004 22:56:14 +0100, "Nick" <no****@nnn.com > declaimed
the following in comp.lang.pytho n:

Let's try some words other than the formal explanations already
given...
---- test.py ----

g = 0
di = {}

def test():
global g
This essentially means you can rebind the global g, and have it
take effect in the outer scope.
di[g] = 1
This is not a rebinding of di, but a component access into the
di object. Since there is no local di object, Python goes out to the
outer scope to find it... You have "opened" the di "box", and stuck
something inside the box -- but the box isn't being changed (whereas: di
= {g:1} is changing the box itself).
g += 1
and this rebinds "g" to a new integer derived from incrementing
the original binding.
-- =============== =============== =============== =============== == <
wl*****@ix.netc om.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
=============== =============== =============== =============== == <