0

I'm having this strange problem.

I have a global var called items that I want to use inside my functions. Sometimes the functions may/may not edit the value of items. Normally I can access this global var just fine, but in some cases it doesn't seem to read the value, and that I need to put the word global in front of it for the local scope. Does anyone know why this happen?

My code is similar to this:

items = []

def func1():
    items = [3,3,3,3,3]

def func2():
    print items

func1()
func2()

Sometimes I would need to put global inside the func1 for it to work, so something like:

def func1():
    global items
    items = [3,3,3,3,3]

It's just really confusing to me as I can't seem to signify when I should/should not use the keyword global until I run the program and run into bugs as my function uses the wrong value of items.

Kil
  • 29
  • 3
  • You can always **read** from parent scopes. If you want to **write** to parent scopes, you need to make that explicit with `global`. – deceze Oct 04 '16 at 14:21
  • In `func1` *assignment* is used on `items`. Normally assignment (and other binding actions, such as arguments to a function or using a name in a `for` loop) marks a name as *local*. You need a `global name` statement to override that decision. – Martijn Pieters Oct 04 '16 at 14:21

0 Answers0