A leaf function performs one small, clearly defined task without calling custom helper functions. It may use Python’s built-in functions. In a call tree, it sits at the edge because no further custom calls leave it. section 3.5
Good leaf functions usually have these properties:
- They perform one task, such as computing a sphere’s volume, finding the largest list value, or checking whether a value appears. section 3.6.1
- They have clearly defined behavior, with inputs, processing, and an expected output that can be described briefly. section 3.6.1
- They avoid combining unrelated operations. Finding and removing the largest value, for example, is better split into two leaf functions. section 3.6.2
- They remain small enough that excessive code length signals an unclear task or a need for decomposition. section 3.6.1
A temperature-conversion leaf function
A function that converts Fahrenheit to Celsius has one input, one defined calculation, and one returned result. It is a leaf function because the calculation does not require another custom function. Similar examples include checking list membership and inserting a value at a chosen location. section 3.7 section 3.6.2
Leaf functions also provide the foundation for larger programs. Problem decomposition breaks a broad task into smaller functions; implementation then proceeds from the leaf functions upward, so larger functions can depend on already-implemented subtasks. Test leaf functions with varied inputs before relying on them elsewhere. section 7.7 section 7.9 section 3.8
Listing 3.1 Code to demonstrate how Python handles function calls
def funct1():
print("there")
funct2()
print("friend")
funct3()
print("")
def funct2():
print("my")
def funct3():
print(".")
def funct4():
print("well")
print("Hi") #1
funct1()
print("I'm")
funct4()
funct3()
print("")
print("Bye.")
Trace how coordinating and leaf functions appear in a Python function-call tree; funct2, funct3, and funct4 are leaf functions. section 3.5
