How does Python print a variable that is out of scope

喜欢而已 提交于 2019-12-08 02:50:04

问题


I have the following function in Python that seems to be working:

def test(self):
    x = -1
    # why don't I need to initialize y = 0 here?
    if (x < 0):
        y = 23

    return y

But for this to work why don't I need to initialize variable y? I thought Python had block scope so how is this possible?


回答1:


This appears to be a simple misunderstanding about scope in Python. Conditional statements don't create a scope. The name y is in the local scope inside the function, because of this statement which is present in the syntax tree:

y = 23

This is determined at function definition time, when the function is parsed. The fact that the name y might be used whilst unbound at runtime is irrelevant.

Here's a simpler example highlighting the same issue:

>>> def foo():
...     return y
...     y = 23
... 
>>> def bar():
...     return y
... 
>>> foo.func_code.co_varnames
('y',)
>>> bar.func_code.co_varnames
()
>>> foo()
# UnboundLocalError: local variable 'y' referenced before assignment
>>> bar()
# NameError: global name 'y' is not defined



回答2:


It seems that you misunderstood this part of Python's documentation:

A Python program is constructed from code blocks. A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition.
...
A scope defines the visibility of a name within a block. If a local variable is defined in a block, its scope includes that block.

So in this case block is something completely different from visual blocks of your code. Thereby if, for, while statements doesn't have their own scopes. But it is worth noting that comprehensions and generator expressions are implemented using a function scope, so they have their own scopes.




回答3:


There is actually no block scope in python. Variables may be local (inside of a function) or global (same for the whole scope of the program).

Once you've defined the variable y inside the 'if' block its value is kept for this specific function until you specifically delete it using the 'del' command, or the function exits. From the moment y is defined in the function, it is a local variable of this function.




回答4:


As in What's the scope of a Python variable declared in an if statement?: "Python variables are scoped to the innermost function or module; control blocks like if and while blocks don't count."

Also useful: Short Description of the Scoping Rules?



来源:https://stackoverflow.com/questions/39438573/how-does-python-print-a-variable-that-is-out-of-scope

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!