I donβt know if this chain of functions is as strong as the chain being called, but since the functions are calling, I think no harm has been done. Anyway, I can think of it in two ways:
Subclassing int and defining __call__ :
The first method would be with a custom subclass of int , which defines __call__ , which returns a new instance of itself with an updated value
class CustomInt(int): def __call__(self, v): return CustomInt(self + v)
The add function can now be defined to return an instance of CustomInt , which, as the called one, which returns the updated value of itself, can be called sequentially:
>>> def add(v): ... return CustomInt(v) >>> add(1) 1 >>> add(1)(2) 3 >>> add(1)(2)(3)(44)
In addition, as a subclass of int return value preserves the behavior of __repr__ and __str__ int s. However, for more complex operations, you must define other passes accordingly.
As @Caridorc noted in a comment, add can also simply be written as:
add = CustomInt
Renaming the class to add instead of CustomInt also works the same way.
Define a closure, an additional call is required to get the value:
The only other way I can think of involves a nested function that requires an additional empty argument call to return the result. I am not using nonlocal and prefer to attach attributes to function objects to make it portable between Pythons:
def add(v): def _inner_adder(val=None): """ if val is None we return _inner_adder.v else we increment and return ourselves """ if val is None: return _inner_adder.v _inner_adder.v += val return _inner_adder _inner_adder.v = v
This continuously returns itself ( _inner_adder ), which, if val supplied, increments it ( _inner_adder += val ), and if not, returns the value as is. As I mentioned, an extra call () is required to return an extra value:
>>> add(1)(2)() 3 >>> add(1)(2)(3)()