473,602 Members | 2,811 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1169
"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}
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.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 <
=============== =============== =============== =============== == <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.ne tcom.com/> <

Jul 18 '05 #4

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

Similar topics

59
3901
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 candidate for Python 3000 yet? Chris
8
2448
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 his name, the data is stuffed into a variable that is dimmed in a module, and the user is "logged in". From time to time, though, Access forgets the value! There is no other place in the database where the variable is written. This is happening...
7
6139
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 that kind of statement as a declaration that can be in a header file used in multiple compilation units. Which of these is correct? Is this something that has changed between different standards?
17
2439
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 but what method would I use to load the entries from the xml file into memory and make them quickly accessible globally in the web code? Just need to know what functions specifically I should start reading about! Thx
7
2299
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 executed the example: # db2 -td@ -f FILENAME. When an single Insert into table fails, the table gets empty. Could anybody shed some light on this ?
3
2271
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 window) ++num;
16
1710
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 (Microsoft Access 2000) file that I am guessing is a compiled binary written in Visual Basic for Applications (VBA). I've done a fairly decent amount of VBA myself but mostly in the Excel, Word and Power Point environments. This is the first...
6
1674
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - Why doesn't the global variable "divId" always refer to the element with id="divId"? ----------------------------------------------------------------------- Microsoft introduced a shortcut that can be used to reference elements which include an ID attribute where the ID becomes a global variable. Some browsers reproduce this behaviours but some, most...
18
1609
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
7993
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7920
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8404
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8054
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8268
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6730
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5867
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5440
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
1254
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.