Block scope in Python Block scope in Python python python

Block scope in Python


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.x))


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, generator expression, dict comprehension, set comprehension and in Python 3.x also for each list comprehension. Apart from these, there are no nested scopes inside of functions.


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:

def my_func():    shared_variable = calculate_thing()    def do_first_thing():        ... = shared_variable    do_first_thing()    def do_second_thing():        foo(shared_variable)        ...    do_second_thing()

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.