Writing explicit types on function parameters
The Python language allows us to write functions (and classes) which are entirely generic with respect to data type. Consider this function as an example:
def temperature(*, f_temp=None, c_temp=None): if c_temp is None: return {'f_temp': f_temp, 'c_temp': 5*(f_temp-32)/9} elif f_temp is None: return {'f_temp': 32+9*c_temp/5, 'c_temp': c_temp} else: raise Exception("Logic Design Problem")
This follows three recipes shown earlier: Using super flexible keyword parameters, Forcing keyword-only arguments with the * separator from this chapter, and Designing complex if...elif chains from Chapter 2, Statements and Syntax.
This function will work for argument values of any numeric type. Indeed, it will work for any data structure that implements the +
, -
, *
, and /
operators.
There are times when we do not want our functions to be completely generic. In some cases, we would like to make...