How can one create new scopes in python

Why do you want to create new scopes in python anyway?

The normal reason for doing it in other languages is variable scoping, but that doesn't happen in python.

if True:
    a = 10

print a

In Python, scoping is of three types : global, local and class. You can create specialized 'scope' dictionaries to pass to exec / eval(). In addition you can use nested scopes (defining a function within another). I found these to be sufficient in all my code.

As Douglas Leeder said already, the main reason to use it in other languages is variable scoping and that doesn't really happen in Python. In addition, Python is the most readable language I have ever used. It would go against the grain of readability to do something like if-true tricks (Which you say you want to avoid). In that case, I think the best bet is to refactor your code into multiple functions, or use a single scope. I think that the available scopes in Python are sufficient to cover every eventuality, so local scoping shouldn't really be necessary.

Tags:

Python

Scope