Today our topic is: function in statement.
Here’s the video version:
Well, this is probably one of the topics you could do without, because there are other ways to get similar results, however it’s useful to know what’s going on if you come across code where a function actually is defined inside a statement.
The def Keyword
Well, to start off, what is def in Python? Yes, it’s the keyword we use to define a function, but, what some people do not always realize, it’s also a full-fledged statement. When this statement is executed, a new function object is created and assigned to a name (which is the name of the function that’s being defined).
We usually define functions in global scope, sometimes inside other functions. This is how def is usually used, but as def is a statement, you can use it wherever a statement can be used, also inside other statements like the conditional if statements or the loops.
Function in if Statement
First, let’s see what’s going on if we nest def inside an if statement:
version1 = True
if version1:
def show_message():
print("Version 1 was chosen.")
else:
def show_message():
print("Version 2 was chosen.")
show_message()
Here’s the output:
Version 1 was chosen.
In this example we’ll create a different version of the show_message function depending on the conditional test and then we will call it. Let’s change version1 to False and run the code again. Now the output is:
Version 2 was chosen.
The function object is only created when the def statement is reached in the code.
Function in Loop
Here’s an example with the for loop:
# empty list of functions
functions = []
for n in range(1, 6):
def hi(x):
print("hi " * x)
# We can attach attributes to functions.
hi.number = n
# All the functions in the functions list will be identical
# except for their number attribute.
functions.append(hi)
for f in functions:
f(f.number)
Output:
hi
hi hi
hi hi hi
hi hi hi hi
hi hi hi hi hi
Let me emphasize it one more time: there are not extremely many use cases for using the def statement inside other statements, especially loops. But it doesn’t hurt to know it’s possible in order to not be taken aback when it pops up somewhere.
An exception to this are other functions because defining functions inside other functions is relatively common practice. But this is a subject worth handling in its own right.