Loop-and-a-half (Re: Curious assignment behaviour)

Jyrinx jyrinxatmindspringdotcom
Sat Oct 13 03:18:03 CEST 2001


> | Or, if you didn't want to make an extra branch and didn't want the
> | uninitialized-i problem, why not just initialize it to 0 before the
loop?
>
> Good practice for sure, but I think the point may have been that
> you shouldn't have to go to so much extra trouble, for safe code.
> You pretty much had to anticipate the problem, to think to make
> those provisions for it, and if 0 items is an exceptional case,
> you'd be very likely to to neglect them.  Once this potential occurs
> to you, it's very easy to solve that problem.

Okay, granted. Somehow, though, I doubt C(++) in general is much better in
terms of being "natural" like this ... :-)

(and I would guess that the veteran Python junkie would get used to this
sort of initialization, no?)

> Here's an idea - suppose the block has its own scope!  Now a reference
> to "i" is illegal outside the block.  More or less like global scope
> vs. function local - if i was assigned to prior to the block, then the
> binding is inherited by the block, but new names are bound in the block
> scope.  Not just the for variable, any assignment - after all, the
> problem is exactly the same.  If you don't know whether you're going
> to execute the block even once, then you need to provide defaults, as
> you did in your example.  That might get a bit tedious, but now we're
> talking about helping people use good programming practices (forcing
> them to, that is.)

Well, this is precisely what happens in C, right (for variables declared in
the loop)? Personally, I like that kind of strict scoping - it indicates
that a variable introduced inside a loop is there on a temporary basis, and
has no purpose being used outside of it. If the programmer must initialize
the variable before the loop because he intends to use it after the loop, it
makes it clearer to a reader, anyway, since the reader knows immediately
that the loop iterator is somehow an important part of the result of the
loop.

Jyrinx
jyrinx at mindspring dot com





More information about the Python-list mailing list