Reasoning behind nested scope

Andy Baker andy at andybak.net
Tue Aug 3 07:26:15 EDT 2004


Hi there,

I'm learning Python at the moment and trying to grok the thinking behind
it's scoping and nesting rules. 

I was googling for nested functions and found this Guido quote:
(http://www.python.org/search/hypermail/python-1993/0343.html)

"This is because nested function definitions don't have access to the
local variables of the surrounding block -- only to the globals of the
containing module. This is done so that lookup of globals doesn't
have to walk a chain of dictionaries -- as in C, there are just two
nested scopes: locals and globals (and beyond this, built-ins).
Therefore, nested functions have only a limited use. This was a
deliberate decision, based upon experience with languages allowing
arbitraries nesting such as Pascal and both Algols -- code with too
many nested scopes is about as readable as code with too many GOTOs.
And, of course, in Python, the "proper" way is to use an
object-oriented programming style"

This sounds reasonable to me although nested scope always struck me as more
natural and intuitive ('Don't be surprising')

I was wondering how the balance changed in favour of nested scope? What
changed people's minds about 'readability' vs other factors? Are nested
scopes still regarded as leading to spagetti code etc?

(On a side note is there any way to call a nested function from outside the
parent? I was kind of expecting nested functions to be addressable through
dot notation like methods are but I can see why that wouldn't be quite
right. This might be a better question for the tutor list...)

Andy Baker




More information about the Python-list mailing list