Reasoning behind nested scope

Larry Bates lbates at swamisoft.com
Tue Aug 3 09:53:21 EDT 2004


Ever since my first Fortran class some 30+ years ago
I've always liked nested scopes.  If you want something
to be global, say so in your code.  In Fortran we used
common blocks, in Python you use a global directive.
Making everything global can lead to many name clashes
or you must have lots of unique variable names which
lengthens code and makes reuse more difficult.

Judicious use of OOP and globals seems to be the best
approach.  The more I learn/use OOP the less I seem
to require globals, but there are some times they
seem a preferable solution.

I don't believe there is any way to call nested
functions from outside their parent.  If you need
something like that, make the function a class and
make the nested function a method of the class.

HTH,
Larry Bates
Syscon, Inc.


"Andy Baker" <andy at andybak.net> wrote in message
news:mailman.1087.1091532385.5135.python-list at python.org...
> 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