question 325 Decorators & Context Managers · medium
Convert arguments before the call
Values from CSV files arrive as text, so every pricing function starts by converting its arguments. Write a decorator factory coerce_args(*converters): the n-th converter is applied to the n-th positional argument before the call; arguments beyond the converters, and keyword arguments, are passed unchanged. A conversion error (ValueError) reaches the caller. The starter applies it as @coerce_args(float, int) to line_total(price, quantity).
Factory
coerce_args(*converters); converters are functions such as float, int, str.stripApplied to
line_total(price, quantity), which returns price * quantityIdentitythe decorated function keeps its name and docstring
Examples
callline_total('7.49', '3')returns22.47
callline_total('31.5', '2')returns63.0
callline_total(12, '4')returns48