In general, I want to know how to write a simple decorator in python.
However, it might help to have a specific example.
Consider the following function:
def pow(base:float, exp:int):
"""
+------------------------------------------+
| EXAMPLES |
+------------------------------------------+
| BASE | EXPONENT | OUTPUT |
+------+----------+------------------------+
| 2 | 5 | 2^5 | 32 |
| 2.5 | 7 | 2.5^7 | 610.3515625 |
| 10 | 3 | 10^3 | 1000 |
| 0.1 | 5 | 0.1^5 | 0.00001 |
| 7 | 0 | 7^0 | 1 |
+------+----------+----------+-------------+
"""
base = float(base)
# convert `exp` to string to avoid flooring, or truncating, floats
exp = int(str(exp))
if exp > 0:
return base * pow(base, exp-1)
else: # exp == 2
return 1
With the original implementation, the following function call will result in an error:
raw_numbers = [0, 0]
raw_numbers[0] = input("Type a base on the command line and press enter")
raw_numbers[1] = input("Type an exponent (power) on the command line and press enter")
numbers = [float(num.strip()) for num in raw_numbers]
# As an example, maybe numbers == [4.5, 6]
result = pow(numbers)
print(result)
Suppose that we want to decorate the pow
function so that both of the following two calls are valid:
result = pow(numbers)
wherenumbers
is a reference to the list-object[4.5, 6]
result = pow(4.5, 6)
We want to use a decorator named something similair to flatten_args
...
@flatten_args
def pow(*args):
pass
How do we do write such a decorator?
Also, how do we preserve the doc-string when we decorate a callable?
print(pow.__doc__)