pythonscope

Block scope in Python


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?


Solution

  • No, there is no language support for creating block scope.

    The following constructs create scope:

    • module
    • class
    • function (incl. lambda)
    • generator expression
    • comprehensions (dict, set, list (in Python 3))