Function Calls Related Tips
Learn function calls-related tips in Python.
Let the caller print
Functions or methods are usually considered units of computation. They take the arguments, apply algorithms to them, compute the results, and return them to the caller.
If a function prints the calculated result instead of returning it, the caller can’t use the result for further computations. Moreover, the caller can be made to believe that what the function returns is the result. Here’s an incorrect way to produce a result:
def add1(x):print(x+1)# There is an implicity return None on this line!y= add1(10)print(y)
Let’s try the correct way:
def add1(x):return x+1y=add1(10)print(y)
Aside from the correct and incorrect ways, there’s also a questionable way when a function prints the result and then returns it:
def add1(x):print(x+1)return x+1y=add1(10)print(y)
The function above, while correct, combines computation and presentation. It always displays the result (and perhaps some other messages) and returns the result to the caller. The caller has no control over the function’s printout.
Because printing is slow, if we call a talkative function in a loop, our code’s performance may significantly decrease. Also, it may be hard to see essential results buried in the sea of chatter. Let the caller of the function decide whether the returned value is worth printing.
We may still want to have an option of printing the result before returning it, which would be useful for debugging). Do so by making printing optional and controllable by the caller.
def add1(x, debug=None):if debug:print(x+1)return x+1y = add1(10)y = add1(10, True)print(y)
When we enable printing within a function, we should add an explanatory message to each printout:
print(f'This is x+1 in function add1: {x+1}')
Understand optional and keyword parameters
Python allows us to write functions that take required positional parameters, optional positional parameters, and keyword parameters. A parameter may have a default value. If we don’t provide the actual value for a ...