Confusion re "global" statement

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Chris Stromberger

    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
  • Michael Peuser

    #2
    Re: Confusion re "global&qu ot; statement


    "Chris Stromberger" <bit_bucket5@ho tmail.com> schrieb im Newsbeitrag
    news:l2g4lvgam2 vlqkk78ep03rlpm v3dn3ni03@4ax.c om...[color=blue]
    > 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".[/color]

    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


    Comment

    Working...