Here is a python module,
#a.py
def bar():
print x #x not defined, apparently will result in an error
def foo():
pass
if __name__ == '__main__':
foo()
The above module can be run ($ python a.py) without any error. Why? Just because bar is not used in __main__?
But bar‘s definition is executed, isn’t it?
Yes,
bar‘s definition is executed, but the definition doesn’t contain an error. It is valid Python to define a function that refers to globals that don’t yet exist, so long as they exist when the function is called. Consider this:This does not result in an error. And this is only sensible, since even if
xexists at the time the function is defined, there is nothing to stop you usingdelon it later. The point whenxneeds to be defined is whenbaris called (if ever), not whenbaris defined.If Python did work the way you are suggesting, then it would be impossible to define mutually recursive functions without weird hacks like temporarily binding one name to
None, then defining both functions.EDIT: To elaborate on Ignacio’s answer to the Alcott’s question in the comments, yes syntax errors are caught before the function can be executed, but they’re actually caught before it can be defined either.
When Python loads a file, it parses the entire contents into statements and then executes the statements one at a time. A syntax error means it was unable to successfully figure out what statements the file contains, so it can’t execute anything. So the error will occur when the file is loaded, which means either when you directly run it with the interpreter, or when you
importit.This pre-processing step is known as “compile time”, even though Python is not normally thought of as a compiled language; it is technically compiled to a byte code format, but this is almost entirely uninteresting because the byte code pretty much just directly represents the source code statements.