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

后端 未结 2 649
耶瑟儿~
耶瑟儿~ 2021-01-28 18:06

I have read the following posts but I am still unsure of something.

  1. Python Compilation/Interpretation Process

  2. Why python compile the source to b

相关标签:
2条回答
  • 2021-01-28 18:44

    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.

    0 讨论(0)
  • 2021-01-28 18:58

    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

    0 讨论(0)
提交回复
热议问题