Global surprise

N

Nick

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}
instead of
2 {}

Thanks.
N.

---- test.py ----

g = 0
di = {}

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

test()
test()

print g, di
 
P

Paul Watson

Nick said:
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}
instead of
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
Type "copyright", "credits" or "license" for more information..... global g
.... di[g] = 1
.... g += 1
....2 {1: 1, 0: 1}
 
B

bruno modulix

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}
instead of
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
is a Bad Thing(tm) BTW).

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
 
D

Dennis Lee Bieber

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).

and this rebinds "g" to a new integer derived from incrementing
the original binding.


--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top