Block scope in Python

2019-01-13 12:19发布

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?

标签: python scope
4条回答
贼婆χ
2楼-- · 2019-01-13 12:22

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.

查看更多
SAY GOODBYE
3楼-- · 2019-01-13 12:28

No, there is no language support for creating block scope. The only means to create scope is functions, classes or modules.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-01-13 12:38

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.

查看更多
冷血范
5楼-- · 2019-01-13 12:44

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

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

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.

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

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.

查看更多
登录 后发表回答