Suppose I have two functions one after another in the same python file:
def A(n):
B(n-1)
# if I add A(1) here, it gives me an error
def B(n):
if n <= 0:
return
else:
A(n-1)
When the interpreter is reading A
, B
is not yet defined, however this code does not give me an error. This confuses me, because I thought that Python programs are interpreted line by line. How come the attempt to call B
within A
doesn't give an error immediately, before anything is called?
My understanding is that, when def
is interpreted, Python adds an entry to some local name space locals()
with {"function name": function address}
, but as for the function body, it only does a syntax check:
def A():
# this will give an error as it isn't a valid expression
syntax error
def B():
# even though x is not defined, this does not give an error
print(x)
# same as above, NameError is only detected during runtime
A()
Do I have it right?
SyntaxError
will be caught at compile time, but most other errors (NameError
,ValueError
, etc.) will be caught only at runtime, and then only if that function is called. – Edmeadef f(): sytax error
does product an error... – Champac