Velocity Reviews > Function Name Resolution Problem

# Function Name Resolution Problem

Haoyu Zhang
Guest
Posts: n/a

 11-03-2003
Dear Freinds,
I am learning Python throught the book "Learning Python" published
by O'Reilly. In its 4.6.2, the author gave an example about incorrect
use of a recursive function. Let me copy the content of the book as
follows.

---------------------------------------------------------------------
>>> def outer(x):

.... print i, # i is in inner's local
.... if i: inner(i-1) # not in my local or global!
.... inner(x)
....
>>> outer(3)

3
Traceback (innermost last):
File "<stdin>", line 1, in ?
File "<stdin>", line 5, in outer
File "<stdin>", line 4, in inner
NameError: inner

This won't work. A nested def really only assigns a new function
object to a name in the enclosing function's scope (namespace).
Within the nested function, the LGB three-scope rule still applies
for all names. The nested function has access only to its own
local scope, the global scope in the enclosing module, and the
built-in names scope. It does not have access to names in the
enclosing function's scope; no matter how deeply functions nest,
each sees only three scopes.

For instance, in the example above, the nested def creates the
name inner in the outer function's local scope (like any other
assignment in outer would). But inside the inner function, the
name inner isn't visible; it doesn't live in inner's local scope,
doesn't live in the enclosing module's scope, and certainly isn't
a built-in. Because inner has no access to names in outer's scope,
the call to inner from inner fails and raises an exception.
---------------------------------------------------------------------

However, when I tested it in my python, it works correctly. So is
it because the standard changes? Or any other reasons? The version
in our university's server is 2.2.1.

Thanks a lot for your help.

Best,
Haoyu

Alex Martelli
Guest
Posts: n/a

 11-04-2003
Haoyu Zhang wrote:

> Dear Freinds,
> I am learning Python throught the book "Learning Python" published
> by O'Reilly. In its 4.6.2, the author gave an example about incorrect

...
> However, when I tested it in my python, it works correctly. So is
> it because the standard changes? Or any other reasons? The version
> in our university's server is 2.2.1.

"Learning Python" is describing Python 1.5.2 -- back then, things
did indeed work as the book says. Many years have passed since,
and a second edition of "Learning Python" (updated to 2.2 at least,
perhaps with some notes on the tiny additions of 2.3 wrt 2.2) will
be out in December (latest estimate -- they're WAY late wrt the
earlier estimates, which were to be several months ago).

Alex