[Tutor] functions

Kalle Svensson kalle@lysator.liu.se
Sun Dec 1 11:53:01 2002


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

[Yann Le Du]
> > Exercise for the interested reader: What will this code print?
> > Why?
> >
> > >>> d = 'foo'
> > >>> def func():
> > ...     print d
> > ...     d = 'bar'
> > ...     print d
> 
> I thought this would print 'foo' then 'bar' but actually it just
> fails :
> 
> UnboundLocalError: local variable 'd' referenced before assignment
> 
> Apparently, it is the d='bar' assignment that conflicts with the
> print d just above. This means that Python looks forward,
> understands that d is local because of d='bar' , then goes back to
> print d and then says that d is not yet defined ?

Yes.  This is caused by an optimization in the Python byte code
compiler.  When compiling a function, it looks for all variables that
are defined either in the argument list (none in the example) or in
the body via assignment.  It then compiles references to these
variables to the opcode LOAD_FAST, which only looks in the local
namespace.  This makes references to arguments and other local
variables faster, but also creates the observed problem.

I'm not a Python guru, and I could well be wrong about the details.
In that case, I hope somebody will correct me.

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/>

iD8DBQE96j5KdNeA1787sd0RApVtAKCU0Nyz91AirfnmvjT0yuJ2GnztMACgmx4b
DYj8OElGSrhnyJWyDDOatmw=
=spSL
-----END PGP SIGNATURE-----