Understanding how Python “Compiles” or “Interprets” Function Objects

主宰稳场 提交于 2019-12-02 08:25:39

When the interpreter reads a function, for each "name" (variable) it encounters, the interpreter decides if that name is local or non-local. The criteria that is uses is pretty simple ... Is there an assignment statement anywhere in the body to that name (barring global statements)? e.g.:

def foo():
    x = 3  # interpreter will tag `x` as a local variable since we assign to it here.

If there is an assignment statement to that name, then the name is tagged as "local", otherwise, it gets tagged as non-local.

Now, in your case, you try to print a variable which was tagged as local, but you do so before you've actually reached the critical assignment statement. Python looks for a local name, but doesn't find it so it raises the UnboundLocalError.

Python is very dynamic and allows you to do lots of crazy things which is part of what makes it so powerful. The downside of this is that it becomes very difficult to check for these errors unless you actually run the function -- In fact, python has made the decision to not check anything other than syntax until the function is run. This explains why you never see the exception until you actually call your function.


If you want python to tag the variable as global, you can do so with an explicit global1 statement:

x = 3
def foo():
  global x
  print x
  x = 2

foo()  # prints 3
print x  # prints 2

1python3.x takes this concept even further an introduces the nonlocal keyword

mgilson got half of the answer.

The other half is that Python doesn't go looking for errors beyond syntax errors in functions (or function objects) it is not about to execute. So in the first case, since f() doesn't get called, the order-of-operations error isn't checked for.

In this respect, it is not like C and C++, which require everything to be fully declared up front. It's kind of like C++ templates, where errors in template code might not be found until the code is actually instantiated.

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