user3885884
user3885884

Reputation: 395

Calling a function before declaring its body in python 3.x

I know that in python, all functions must be defined before any are used. So this code will result in an error:

hello()
def hello():
    print('Hi!')

But in a code like the one bellow:

def func():
    hello()

def hello():
    print('Hi!')

func() 

The hello() function is called by func() before it's defined and it still works and I don't understand why.

So can you please explain the above behavior and thanks in advance.

Upvotes: 1

Views: 135

Answers (3)

YOBA
YOBA

Reputation: 2807

Python is an interpreted language, therefore it is interpreted line by line,

Both your examples follow the same logic,

in the second one,

func and hello have already been interpreted, so when you call func() they both are known and for that executed.

def func():
    hello()

--> At this level func is known but not executed (called) yet

def hello():
    print('Hi!')

--> At this level, both func and hello are known but not executed (called) yet

func()

--> Finally when you call func, no matter what order func and hello are. They are known and have an address in memory.

Upvotes: 3

ForceBru
ForceBru

Reputation: 44838

I think this is because Python code is parsed top-down, and whenever the interpreter sees a function call, it has to execute it right away, so if it's not defined (yet), this will be an error.

On the other hand, if this function isn't being called now, but the call appears in a definition of another function, the interpreter 'says': "Okay, there should be a function called hello, so I'm gonna look for it". If it does find it, it's OK, otherwise it's an error.

Upvotes: 0

Leon
Leon

Reputation: 3036

Defining a new function does not execute it. Hence the hello() function is only called when you call func(), which is done after defining hello().

Upvotes: 3

Related Questions