Confusion re "global" statement

Discussion in 'Python' started by Chris Stromberger, Aug 31, 2003.

  1. 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
     
    Chris Stromberger, Aug 31, 2003
    #1
    1. Advertising

  2. "Chris Stromberger" <> schrieb im Newsbeitrag
    news:...
    > 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
     
    Michael Peuser, Aug 31, 2003
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. wanwan
    Replies:
    3
    Views:
    453
    Alex Martelli
    Oct 14, 2005
  2. Replies:
    0
    Views:
    239
  3. Drew

    If statement confusion

    Drew, Apr 6, 2005, in forum: ASP General
    Replies:
    6
    Views:
    156
  4. Dustin McCormick

    Statement modifiers causing confusion

    Dustin McCormick, Nov 21, 2005, in forum: Ruby
    Replies:
    1
    Views:
    88
  5. Erwin Moller

    local/global scope confusion

    Erwin Moller, Nov 12, 2008, in forum: Javascript
    Replies:
    30
    Views:
    273
    Dr J R Stockton
    Nov 19, 2008
Loading...

Share This Page