Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can one create new scopes in python

Tags:

python

scope

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

like image 778
Boris Gorelik Avatar asked Feb 12 '09 15:02

Boris Gorelik


People also ask

How do you create a scope in Python?

You can do l.a=b=c statements in python, where the b might be something like df['some new column $e=mc^2$'] and you don't want to have to type that all out the next line down.

How many scopes are there in Python?

You will learn about the four different scopes with the help of examples: local, enclosing, global, and built-in. These scopes together form the basis for the LEGB rule used by the Python interpreter when working with variables.


2 Answers

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.

like image 61
batbrat Avatar answered Sep 19 '22 14:09

batbrat


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 
like image 35
Douglas Leeder Avatar answered Sep 21 '22 14:09

Douglas Leeder