Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

temporary scope change

0 views
Skip to first unread message

Edward Elliott

unread,
Apr 18, 2006, 7:26:26 PM4/18/06
to
The only time I miss block delimiters in Python is when I want to
temporarily change the scope of a block. Suppose I have this code:

for x in list1:
i += 1
for y in list2:
print x * i

Ignore the semantics for the moment (yes the code is suboptimal). Say I
need to disable the for y loop for a moment, but I want to keep the print
statement. I'd like to just do this

for x in list1:
i += 1
# for y in list2:
print x * i

and have the print line execute as part of the for x block. In other
words, I want the block with print to be in the scope of the for x loop.
But instead it raises a SyntaxError because the indentation is different.

Changing the indentation here isn't a big deal, but imagine the block
inside y is very long. Imagine you're disabling several blocks or multiple
levels of nested blocks at one time. It quickly becomes a thorny issue.
Using a debugger to disable it at run-time doesn't always help either.

This seems a common enough problem that I suspect there's a python way to
handle it. I don't see a good way without resorting to block delimiters
though, so I'm asking here for ideas.

Apologies if this has been covered before. I did some searches of the
python docs and newsgroup archives but couldn't find anything relevant
(which may say more about my searching abilities than anything else).

Michael Spencer

unread,
Apr 19, 2006, 12:27:10 AM4/19/06
to pytho...@python.org
Edward Elliott wrote:
...

>
> for x in list1:
> i += 1
> # for y in list2:
> print x * i
>
> and have the print line execute as part of the for x block. In other
> words, I want the block with print to be in the scope of the for x loop.
> But instead it raises a SyntaxError because the indentation is different.
>
Just replace:
for y in list2:
with:
if True:

But, in a real debugging situation, y would probably be used in the inner loop,
so you could instead, precede the y loop with:
list2 = [One_object_that_list2_could_contain]

so that that the loop executes once. Once that works, you might then
selectively add items to your temporary list2.

Note that neither the `if` nor the `for` statement actually creates a new scope.

Michael

Edward Elliott

unread,
Apr 19, 2006, 1:08:39 AM4/19/06
to
Michael Spencer wrote:
> Just replace:
> for y in list2:
> with:
> if True:

Of course. I knew it would be blindingly obvious. Sometimes you just
can't shake the blinders off though. Thanks.

> Note that neither the `if` nor the `for` statement actually creates a
> new scope.

Good catch. I'm used to thinking block = scope. Old habits die hard I guess.

0 new messages