Stefan - 2 months ago 17x

Python Question

On codewars.com I encountered the following task:

Create a functionthat adds numbers together when called in succession. So`add`

should return`add(1)`

,`1`

should return`add(1)(2)`

, ...`1+2`

While I'm familiar with the basics of Python, I've never encountered a function that is able to be called in such succession, i.e. a function

`f(x)`

`f(x)(y)(z)...`

`f(x)(y)`

`x`

`g_{x}`

`g_{x}(y)`

`f(x)(y)(z)`

Therefore I'd like to ask you: How do you call this concept and where can I read more about it?

Answer

One suggestion (the way I'd do this) would be with a custom `int`

subclass that defines a `__call__`

which returns a new instance of itself with the updated value:

```
class CustomInt(int):
def __call__(self, v):
return CustomInt(self + v)
```

Function `add`

can now be defined to return that `CustomInt`

instance, which, as a callable, can be called in succession:

```
# as @Caridorc noted in a comment
# add could be simply written as: add = CustomInt
>>> def add(v):
... return CustomInt(v)
>>> add(1)
1
>>> add(1)(2)
3
>>> add(1)(2)(3)(44) # and so on..
50
```

In addition, as an `int`

subclass, the returned value retains the `__repr__`

and `__str__`

behavior of `int`

s.

Maybe this implementation suits you, alternatives likely exist and would be interesting to examine. I don't know whether this is *function* chaining as much as it's *callable* chaining, but, since functions *are* callables I guess there's no harm done.

Source (Stackoverflow)

Comments