block scope?

John Nagle nagle at animats.com
Sat Apr 7 20:13:12 EDT 2007


Paul Rubin wrote:
> John Nagle <nagle at animats.com> writes:
> 
>>    In a language with few declarations, it's probably best not to
>>have too many different nested scopes.  Python has a reasonable
>>compromise in this area.  Functions and classes have a scope, but
>>"if" and "for" do not.  That works adequately.
> 
> 
> I think Perl did this pretty good.  If you say "my $i" that declares
> $i to have block scope, and it's considered good practice to do this,
> but it's not required.  You can say "for (my $i=0; $i < 5; $i++) { ... }"
> and that gives $i the same scope as the for loop.  Come to think of it
> you can do something similar in C++.

     Those languages have local declarations.  "my" is a local
declaration.  If you have explicit declarations, explict block
scope is no problem.  Without that, there are problems.  Consider

     def foo(s, sname) :
         if s is None :
             result = ""
         else :
             result = s
         msg = "Value of %s is %s" % (sname, result)
	return(msg)

It's not that unusual in Python to initialize a variable on
two converging paths.  With block scope, you'd break
code that did that.
	

					John Nagle



More information about the Python-list mailing list