简体   繁体   中英

Python function execution order

I couldn't find any question related to this subject. But does python execute a function after the previous called function is finished or is there in any way parallel execution?

For example:

def a():
    print('a')

def b():
    print('b')

a()
b()

So in this example I would like to know if I can always be sure that function b is called after function a is finished, even if function a is a very long script? And what is the defenition of this, so I can look up documentation regarding this matter.

Thanks

Defining the function doesn't mean its execution. Since you defined a first, the function object for a will be created first, so as for there calls.

You can take it as execution timeline starting from top to bottom.

TLDR: b will only ever run after a is exited.

Each Python thread will only ever execute one thing at a time and respect ordering of expressions and statements. For the most part, this means executing "top-to-bottom", though function definitions, control flow and other elements can affect execution order. Ordering is preserved in any case, however.


Strictly speaking, the Python language only defines the execution order of expressions .

Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.

Neither simple statements nor compound statements define an evaluation order.

However, Python is defined based on a byte code interpreting virtual machine , and the reference implementation is based on a stackbased bytecode evaluation loop . All major implementations of Python preserve the observable behaviour of executing one statement after the other.

There is no parallel execution of functions in python. The above functions will be executed in the same sequence that they were called in regardless of the amount of computation workload of either of the functions.

In python functions are by default executed in the order they appear. However if you call them in a different order they will execute as such. So in your example

def a():
    print('a')
def b():
    print('b')

b()
a()

then b() will execute before a()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM