Python Mystery Theatre -- Episode 2: Así Fue

Raymond Hettinger vze4rx4y at verizon.net
Mon Jul 14 22:30:07 EDT 2003


[Jason Trowbridge]
> Act I
> I didn't know that python formatting could do that!  I've always
> treated it like C's printf-style of statements, as that seems to be
> what it's primarily based off.

That's why this one was included.
Hope everyone learned something new.


> The radix parameter gives the base for the conversion and may be any
> integer in the range [2, 36], or zero. If radix is zero, the proper
> radix is guessed based on the contents of string; the interpretation
> is the same as for integer literals.
>
> That explains the 0 radix and the exception caused by the -1000 radix.
>  So why does it work with a radix of -909?  I presume a bug (which
> probably got fixed in later versions of Python).  I'll have to see if
> this behavior is present under Python 2.3b at home.

The learning points are:

* the 0 prefix indicator for octal is ignored when an explicit base is specified
* specifying zero as a base allows the prefix to have the desired effect
* -909 is an undocumented implementation detail (hackish but not a bug).


> Apparently, os.putenv() doesn't work like I thought.
>
> Ah!  os.putenv() updates the environment, but not the os.environ
> dictionary.  It looks like os.getenv() retrieves the environmental
> variables from os.environ, and just assumes that it is up to date.
> Since it defaults to None if the environmental variable doesn't exist
> in os.environ[], that's what I get.

Those are exactly the learning points.  Congrats.

BTW, the docs do say to update os.environ directly if you want it changed.


> Aha!  So the lambda is looking up f in the current scope when it is
> executed! Instead of binding to the actual function object being
> iterated over in the list comprehension, the lambda is binding to the
> variable 'f' itself?

Yes, but Fred's explanation is much more to the point.

BTW, the example has nothing to do with lambdas, it is all about
nested scopes and binding.  You would experience the same issues
with defs inside a regular for-loop.

A secondary learning point is that list comprehensions overwrite and
expose the loop variable just like an equivalent for-loop.

> (Hey, these are fun!)


I enjoyed reading your response.
This is exactly the way I wanted the mysteries to be solved.
IMO, the newsgroup has been needing to regain some its
humor, curiousity, fun, and sense of playful exploration.


Raymond Hettinger






More information about the Python-list mailing list