Python block scope

When encoding in other languages, you sometimes create a block area, for example:

statement ... statement { statement ... statement } statement ... statement 

One of the goals of (many) is to improve the readability of the code: to show that certain operators form a logical unit or that certain local variables are used only in this block.

Is there an idiomatic way to do the same in Python?

+79
scope python
May 29 '11 at
source share
4 answers

No, there is no language support for creating a scope.

The following constructs create a scope:

  • module
  • the class
  • function (including lambda)
  • generator expression
  • understanding (dict, set, list (in Python 3.x))
+66
May 29 '11 at 13:20
source share
โ€” -

The idiomatic way in Python is to keep your functions short. If you think you need it, refactoring 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. In addition to them, inside functions there are no nested scope.

+35
May 29 '11 at 13:16
source share

You can do something similar to the scope of a C ++ block in Python by declaring a function inside your function and then calling it immediately. 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, this video may convince you.

The basic principle is to cover everything as narrowly as possible without introducing any โ€œgarbageโ€ (additional types / functions) into a wider area than is absolutely necessary - nothing else wants to use the do_first_thing() method, for example , so this should not be outside the scope of the calling function.

+13
Jul 20 '17 at 9:34 on
source share

I agree that there is no block block. But one place in Python 3 makes it SEEM, as if it had a block scope.

What happened, what gave this look? This worked properly in Python 2. But to stop the variable leak in Python 3, they did this trick, and this change makes it look like it has a block scope here.

Let me explain.




According to the idea of โ€‹โ€‹a scope, when we introduce variables with the same name inside the same scope, its value should be changed.

this is what happens in python 2

 >>> x = 'OLD' >>> sample = [x for x in 'NEW'] >>> x 'W' 

But in Python 3, even if a variable with the same name is entered, it does not override, list comprehension acts for some reason as a sandbox and looks like creating a new scope in it.

 >>> x = 'OLD' >>> sample = [x for x in 'NEW'] >>> x 'OLD' 

and this answer goes against the answererer @Thomas statement . The only means to create a scope is functions, classes, or modules, because it looks like another place to create a new scope.

+11
Jun 15 '18 at 23:17
source share



All Articles