When you code in other languages, you will sometimes create a block scope, like this:
statement
...
statement
{
statement
...
statement
}
statement
...
statement
One purpose (of many) is to improve code readability: to show that certain statements form a logical unit or that certain local variables are used only in that block.
Is there an idiomatic way of doing the same thing in Python?
The idiomatic way in Python is to keep your functions short. If you think you need this, refactor your code! :)
Python creates a new scope for each module, class, function or generator expression (in Python 3.x also for list comprehensions). Apart from this, there are no nested scopes inside of functions.
No, there is no language support for creating block scope. The only means to create scope is functions, classes or modules.
You can do something similar to a C++ block scope in Python by declaring a function inside your function and then immediately calling it. For example:
If you're not sure why you might want to do this then this video might convince you.
The basic principle is to scope everything as tightly as possible without introducing any 'garbage' (extra types/functions) into a wider scope than is absolutely required - Nothing else wants to use the
do_first_thing()
method for example so it shouldn't be scoped outside the calling function.I agree that there is no block scope. But one place in python 3 makes it SEEM as if it has block scope.
what happened which gave this look? This was working properly in python 2. but to make variable leakage stop in python 3 they have done this trick and this change makes it look like as if it has block scope here.
Let me explain.
As per the idea of scope, when we introduce variables with same names inside the same scope, its value should be modified.
this is what is happening in python 2
But in python 3 even though the variable with same name is introduced it does not override, the list comprehension acts like a sandbox for some reason and seems like creating a new scope in it.
and this answer goes against the answerer @Thomas's statement The only means to create scope is functions, classes or modules because this looks like one other place of creating a new scope.