Skip to content Skip to sidebar Skip to footer

Understanding How Python "compiles" Or "interprets" Function Objects

I have read the following posts but I am still unsure of something. Python Compilation/Interpretation Process Why python compile the source to bytecode before interpreting? If I

Solution 1:

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.:

deffoo():
    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 global statement:

x = 3deffoo():
  global x
  print x
  x = 2

foo()  # prints 3print x  # prints 2

Solution 2:

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.

Post a Comment for "Understanding How Python "compiles" Or "interprets" Function Objects"