unintuitive for-loop behavior

BartC bc at freeuk.com
Fri Sep 30 10:45:11 EDT 2016


On 30/09/2016 15:01, Chris Angelico wrote:
> On Fri, Sep 30, 2016 at 10:33 PM, Steve D'Aprano
> <steve+python at pearwood.info> wrote:
>> To me, "make for-loops be their own scope" sounds like a joke feature out of
>> joke languages like INTERCAL. I'm not aware of any sensible language that
>> does anything like this.
>>
>> No, wait a minute, I tell a lie, I recall Chris Angelico mentioning that one
>> of his favourite languages, Pike or REXX, does it. I forget which.
>
> In C-like languages (including Pike), you can legally define a
> variable at any point, making it visible at that point and all inner
> locations - effectively, every brace becomes a new subscope. It makes
> sense ONLY because variables are declared, no matter where they are
> (globals are declared at module scope, locals at some kind of inner
> scope). So, it's not strictly true that Pike has for loops as their
> own scope, just that C-like languages have a lot of nested scopes.

C likes to make things a bit more complicated:

  int A;
  { A;       // this is the outer A
    int A;
    A;       // this is the inner A
    goto A;
    A:       // this is yet another A
  }

Labels live in a different name-space from other names. I've left out 
struct tags which also have their own name-space, and would allow five 
different A's in that block (an outer and inner 'struct A') rather than 
the three I've shown.

So a single pair of {-} can enclose three (sometimes five) versions of 
the same identifier.

Personally I think function-scope is plenty. Only one possible top-level 
'A' in a function instead of an unlimited number.

(Python allows extra 'A's inside nested functions and classes within 
that function, but that's a bit different.)

-- 
Bartc



More information about the Python-list mailing list