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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With