[Tutor] global statement?

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 15 Aug 2001 00:11:21 -0700 (PDT)


On Wed, 15 Aug 2001, Haiyang wrote:

> Could anyone please tell me WHY function B can't take globalized dictionary
> 'a' as a default value?
> How can I make it work?
> 
> >>> def A():
> ...          global a
> ...          a = {}
> ...          a['happyface']=1
> ...          a['sadface']=99
> ...
> >>> def B(b=a):
> ...          for item in b:
> ...               print b
> ...
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
> NameError: name 'a' is not defined
> 

Try this:

###
>>> def A():
...     global a
...     a = {}
...     a['happyface'] = 1
...     a['sadface'] = 99
...
>>> a = {}
>>> def B(b=a):
...     for item in b:
...         print b
...
>>> B()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in B
TypeError: loop over non-sequence
###

In Python, we create variables by assigning to them. Although A() declares
that somewhere, outside the function, there's a global variable called
'a', B doesn't know that.

The error message is coming from the defintion of B: it's during function
definition time that B will know that 'b' will be 'a'.  Gosh, I feel like
Ayn Rand for some odd reason.


It's sorta similar to the behavior we saw a few messages ago:

###
>>> def testMutableDefaultArg(mylist = []):
...     mylist.append('B is B')
...     return mylist
...
>>> testMutableDefaultArg()
['B is B']
>>> testMutableDefaultArg()
['B is B', 'B is B']
>>> testMutableDefaultArg(['A is A'])
['A is A', 'B is B']
>>> testMutableDefaultArg()
['B is B', 'B is B', 'B is B']
###


If we define a default argument while mixing up a function, Python needs
to know what that value is.

Hope this helps!