Mutable global variables don't get hide in python functions, right?

Posted by aXqd on Stack Overflow See other posts from Stack Overflow or by aXqd
Published on 2010-05-06T14:11:05Z Indexed on 2010/05/06 14:18 UTC
Read the original article Hit count: 216

Filed under:
|

Please see the following code:

def good():
  foo[0] = 9         # why this foo isn't local variable who hides the global one

def bad():
  foo    = [9, 2, 3] # foo is local, who hides the global one

for func in [good, bad]:
  foo = [1,2,3]

  print('Before "{}": {}'.format(func.__name__, foo))
  func()
  print('After  "{}": {}'.format(func.__name__, foo))

The result is as below:

# python3 foo.py
Before "good": [1, 2, 3]
After  "good": [9, 2, 3]
Before "bad" : [1, 2, 3]
After  "bad" : [1, 2, 3]

© Stack Overflow or respective owner

Related posts about python

Related posts about python-3.x