views:

100

answers:

2

Why does Python complain about chrome being referenced before assignment? It does not complain about the dictionary. This is with Python 2.5 if it makes a difference.

def f():
  google['browser'] = 'chrome'
  chrome += 1

google = dict()
chrome = 1
f()

I can make it work with global chrome of course, but I'd like to know why Python does't consider the variable to be assigned. Thanks.

+4  A: 

In the statement

chrome += 1

and it has not been created yet. The variables are created the first time they are assigned. In this case, when python sees the code incrementing 'chrome', it doesn't see this variable at all.

Try rearranging your code as

chrome = 1

def f():
  global chrome
  google['browser'] = 'chrome'
  chrome += 1

google = dict()
f()
pyfunc
@irrelephant: Thanks. A typo missed out the global keyword! corrected.
pyfunc
Thanks. Comments must be at least 15 characters in length.
pdknsk
+1  A: 

It's out of scope: read here

irrelephant
Thanks, I understand.
pdknsk