Python - def Executes at Runtime

Introduction

The Python def is a true executable statement.

When it runs, it creates a new function object and assigns it to a name.

The following code shows that you can nest a function def inside an if statement to select between alternative definitions:

if test: 
    def func():            # Define func this way 
        ... 
else: 
    def func():            # Or else this way 
        ... 
 ... 
func()                     # Call the version selected and built 

def is much like an = statement.

It assigns a name at runtime.

Python functions do not need to be fully defined before the program runs.

def statements are not evaluated until they are reached and run, and the code inside defs is not evaluated until the functions are later called.

Related Topic