Alex Rivera | Logout

How can one create new scopes in python

Asked 2009-02-12T15:53:59.543
37

In many languages (and places) there is a nice practice of creating local scopes by creating a block like this.

void foo()
{
     ... Do some stuff ...

     if(TRUE)
     {
         char a;
         int b;

         ... Do some more stuff ...
     }

     ... Do even more stuff ...
 }

How can I implement this in python without getting the unexpected indent error and without using some sort of if True: tricks

Edit
Report

1 Answer

3

variables in list comprehension (Python 3+) and generators are local:

>>> i = 0
>>> [i+1 for i in range(10)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> i
0

but why exactly do you need this?

answered 2009-02-12T15:57:57.430

Your Answer