block scope?

MRAB google at mrabarnett.plus.com
Sun Apr 8 02:54:42 CEST 2007


On Apr 7, 8:50 am, James Stroud <jstr... at mbi.ucla.edu> wrote:
> Paul Rubin wrote:
> > John Nagle <n... 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++.
>
> How then might one define a block? All lines at the same indent level
> and the lines nested within those lines?
>
> i = 5
> for my i in xrange(4):
>    if i:             # skips first when i is 0
>      my i = 100
>      if i:
>        print i       # of course 100
>      break
>    print i           # i is between 0 & 3 here
> print i             # i is 5 here
>
> Doesn't leave a particularly bad taste in one's mouth, I guess (except
> for the intended abuse).
>
How about something like this instead:

i = 5
block:
    for i in xrange(4):
        if i:             # skips first when i is 0
            block:
                i = 100
                if i:
                    print i       # of course 100
                break
        print i           # i is between 0 & 3 here
print i             # i is 5 here

Any variable that's assigned to within a block would be local to that
block, as it is in functions.




More information about the Python-list mailing list