[Tutor] Re: functions

Derrick 'dman' Hudson dman@dman.ddts.net
Sun Dec 1 13:06:02 2002


--gKMricLos+KVdGMg
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Sun, Dec 01, 2002 at 05:52:31PM +0100, Kalle Svensson wrote:
| [Yann Le Du]
| > > Exercise for the interested reader: What will this code print?
| > > Why?
| > >
| > > >>> d =3D 'foo'
| > > >>> def func():
| > > ...     print d
| > > ...     d =3D 'bar'
| > > ...     print d
| >=20
| > I thought this would print 'foo' then 'bar' but actually it just
| > fails :
| >=20
| > UnboundLocalError: local variable 'd' referenced before assignment

| Yes.  This is caused by an optimization in the Python byte code
| compiler.

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

It's not an optimization, really, it's the addition of nested lexical
scopes.  If you use python <=3D 2.1 you'll get 'foo' then 'bar'.  If you
use python 2.1 with "from __future__ import nested_scopes" or python
>=3D 2.2 you'll get the above error.  There may be some optimizations
involved, but the real change was the nested scopes.

-D

--=20
Stay away from a foolish man,
for you will not find knowledge on his lips.
        Proverbs 14:7
=20
http://dman.ddts.net/~dman/

--gKMricLos+KVdGMg
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj3qUsEACgkQO8l8XBKTpRTRiQCgnCuAz1gWLaIzMjt822GirmIW
hvEAoLhWZ+p3r5HsjXgPslqF7/t0g1g+
=fhQL
-----END PGP SIGNATURE-----

--gKMricLos+KVdGMg--