473,321 Members | 1,667 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,321 software developers and data experts.

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}
instead of
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 1152
"Nick" <no****@nnn.com> wrote in message
news:co**********@namru.matavnet.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}
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.
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}
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
Jul 18 '05 #3
On Wed, 24 Nov 2004 22:56:14 +0100, "Nick" <no****@nnn.com> declaimed
the following in comp.lang.python:

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.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

59
by: seberino | last post by:
I've heard 2 people complain that word 'global' is confusing. Perhaps 'modulescope' or 'module' would be better? Am I the first peope to have thought of this and suggested it? Is this a...
8
by: Mike Turco | last post by:
This is a strange one. I have an app that needs to know who is using the program but there's no need for security. When the program opens a form comes up with a listbox. The user double-clicks...
7
by: Brian Sammon | last post by:
According to my programming textbook, "int a;" at the top level of a file is a definition which shouldn't go in a header file. However, I'm running into a lot of online documentation that treats...
17
by: Davíð Þórisson | last post by:
now in my web I have some global variables to be used in many different subpages, in the old ASP I simply loaded a variables.asp file into memory using the eval() function. Now I'd like to use XML...
7
by: fintudet | last post by:
Hello. During some experimentation with DB2 decimal numbers representations, I have discovered very unexpected behaviour of the global temporary table. Consider this example. Such I had...
3
by: sundew | last post by:
so here is the test case: <head> <script type='text/javascript'> // this function simply returns the number of enumerable namespaces(objects) function numNSpaces(){ var num = 0; for(var i in...
16
by: Sathyaish | last post by:
I am expecting a VBA code module in one of the VBA apps, but much to my astonishment, I don't seem to find my way through it. It seems like I am looking at a fully compiled binary. I have an MDB...
6
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - Why doesn't the global variable "divId" always refer to the element with id="divId"?...
18
by: Donn Ingle | last post by:
Hi, I'm getting myself really confused. I have three classes. Two of them need to reference the third, like so: Canvas ---Stack <--- Thing I am doing this right now: s = Stack()
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.