I want to write a python function my_sum
that extends python's built-in sum
in the following way:
- If a sequence is passed to
my_sum
it behaves like the built-insum
. - If multiple values are passed to
my_sum
, it returns the sum of the values.
Desired output:
my_sum([1, 2, 3]) # shall return 6 (similiar to built-in sum)
my_sum(1, 2, 3) # shall return 6 as well, (sum throws TypeError)
What worked was the following.
def my_sum(*x):
try:
return sum(x) # sums multiple values
except TypeError:
return sum(*x) # sums sequence of values
Is that the pythonic way to accomplish the desired behavior? For me the code looks odd.