469,343 Members | 5,373 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,343 developers. It's quick & easy.

Confusion re "global" statement

This doesn't seem like it should behave as it does without using
"global d" in mod().

d = {}

def mod():
d['hey'] = 3

mod()
print d

When run, it prints {'hey': 3}. Seems like it should print {} w/o
using "global d".

Can someone explain? I guess it has to do with the fact that I'm not
reassigning the name d in the function, but it seems counter-intuitive
that I'm able to modify a global inside the function w/o saying
"global d".

Thanks,
Chris
Jul 18 '05 #1
1 1614

"Chris Stromberger" <bi*********@hotmail.com> schrieb im Newsbeitrag
news:l2********************************@4ax.com...
This doesn't seem like it should behave as it does without using
"global d" in mod().

d = {}

def mod():
d['hey'] = 3

mod()
print d

When run, it prints {'hey': 3}. Seems like it should print {} w/o
using "global d".

Can someone explain? I guess it has to do with the fact that I'm not
reassigning the name d in the function, but it seems counter-intuitive
that I'm able to modify a global inside the function w/o saying
"global d".


Well Chris, it *may* be counter-intuitive. On the other hand it is very
consequent. Think of what happens in an _ordinary_ programming language when
you use a name in a block or subroutine:
- either it is locally defined/declared: the loccal version is taken
- if it is not, the global version is used
- if there is no global version, an error message is issued.

Just the same with Python!

But do we define/declare variables in Python? Yes, by simply assigning a
value to them!

In case of your list note that you do not assign a new value to _d_ but to
just to one of it's items.
Kindly
Michael P
Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

11 posts views Thread by mrbog | last post: by
8 posts views Thread by David Hitillambeau | last post: by
9 posts views Thread by Javaman59 | last post: by
2 posts views Thread by Steve | last post: by
3 posts views Thread by Ernesto | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.