temporary scope change

E

Edward Elliott

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).
 
M

Michael Spencer

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
 
E

Edward Elliott

Michael said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top