nested scopes

Jeremy Hylton jhylton at my-deja.com
Mon Feb 5 13:57:56 EST 2001


In article <mailman.981395193.31631.python-list at python.org>,
  D-Man <dsh8290 at rit.edu> wrote:
> What I wonder about is whether names defined in a try block or a for
> block will still exist outside the block.
>
> Take this Java code for example:
>
> String s ;
> try
> {
> 	s = some_func_that_might_throw() ;
> }
> catch ( ThrownException ex )
> {
> 	s = "Some other value" ;
> }
>
> So you look at it and whether the function throws an exception or not,
> s has been initialized appropriately.  javac won't compile this since
> "s might not be initialized".
>
> In Python, it is much nicer :
>
> try :
> 	s = some_func_that_might_throw()
> except ThrownException :
> 	s = "Some other value"
>
> and everything works as expected.  If the exception was thrown, s will
> have the one value, if not it will have the other.
>
> Will the new nested scopes require me to write:
>
> s = None # make the name exist in this scope first
> try :
> 	...
>
> ?

No.  Nested scopes don't require you to do anything different unless you
actually use nested scopes.  In places where Java would raise a
compile-time error because it can't tell if a name will be used
unitialized, Python will not complain at comile time.  Instead, it will
raise a NameError if an error occurs at run time.  I won't offer any
opinions about which is better.

> I think it is acceptable if variables like loop counters and temps
> inside a loop don't exist in the function's namespace. ie:

Regardless of whether you find it acceptable, the language doesn't work
that way.

> Last quarter I took a class called "Programming Language Concepts"
> that discussed the design of programming languages.  It was the first
> time I had heard of dynamic scoping.  (Actually, I think I saw it
> mentioned in a lisp context, but I didn't know what it meant)  The
> professor didn't know of any situations where it would be
> advantageous, and I couldn't contrive any either.  I was kind of
> surprised when I heard python described as "dynamically scoped"
> because its scoping was really quite natural for me.  The [23]-level
> scoping makes the dynamic scoping almost static and I don't see that
> as a weakness.

Python's scoping rules aren't dynamic, never have been.  (At least not
as long as I've been using the language.)  It used to be that scopes
didn't nest, but that doesn't make scoping dynamic.

>
> I really don't know, at this moment, whether adding nested static
> scopes will strengthen or weaken the language.

PEP 227 has a brief discussion of some benefits, among them that lambdas
are easier to use.  http://python.sourceforge.net/peps/

--
-- Jeremy Hylton, <http://www.python.org/~jeremy/>


Sent via Deja.com
http://www.deja.com/



More information about the Python-list mailing list