[Tutor] functions

Kalle Svensson kalle@lysator.liu.se
Sun Dec 1 09:12:02 2002


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[david, slightly edited for readability]
> why does this work:
> >>> d={}
> >>> d
> {}
> >>> def myfun():
> ...     d[0]='hello'
> ...
> >>> myfun()
> >>> d
> {0: 'hello'}
> 
> but this doesnt?
> 
> >>> d='hello'
> >>> d
> 'hello'
> >>> def myfun():
> ...     d='goodbye'
> ...
> >>> myfun()
> >>> d
> 'hello'
> >>>

It's because dictionary objects are mutable and strings aren't.  A
mutable object is one that can be changed, for example by setting
items.  The line

  d[0] = 'hello'

that looks like a regular assignment really isn't.  It could be
written as

  setitem(d, 0, 'hello')

as well.

This is what happens:

>>> d={}

Bind the name d in the global namespace to a new dictionary object.

...     d[0] = 'hello'

Look up the name d.  There is no d in the function local namespace, so
we go looking in the global namespace and find the dictionary object.
Set item 0 of the dictionary object to 'hello'.

>>> d='hello'

Rebind the name d in the global namespace to a string object.

...     d='goodbye'

Bind the name d in the function local namespace to a string object
with the value 'goodbye'.  This object is then discarded when the
function returns and the local namespace disappears.

If you added the line

  print d

to the function in exaple two, it would lookup d and find a binding in
the local namespace.  It would then print this object, the string
'goodbye'.

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>

iD8DBQE96hindNeA1787sd0RAh2TAJ9zkz/QA/HhElmONJ1CONbGIGQgewCfY10q
29skGK/3xGOdGf0C/0WN000=
=iLVJ
-----END PGP SIGNATURE-----