'Python function "sum" with syntax like: sum() -> 0 sum(1)(2)(3) -> 6

I am new to Python and I need to write function sum with similar syntax:

print(sum())
print(sum(1)(2)(3))
print(sum(1)(2)(3)(-4)(-5))

The output is:

0
6
-3

I tried to write decorator like this:

def sum(a=0):
    res = a
    def helper(b=0):
        nonlocal res
        res += b
        return res
    return helper

But it helps only with fixed quantity of (). So this code works only for: sum(1)(2)->3 and doesn't for sum()-><function sum.<locals>.helper at 0x7fca6de44160> or sum(1)()(3) -> TypeError: 'int' object is not callable I think there should be a decorator with recursion, but i don't know how to realize it



Solution 1:[1]

Finaly, I found my way of solving this task (using only functions):

def sum(x=None):
    value = 0

    def helper(y=None):
        nonlocal value
        if y is None:
            return value
        value += y
        return helper

return helper(x)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gab