In this question I asked about a function composition operator in Python. @Philip Tzou offered the following code, which does the job.
import functools
class Co
I am actually unwilling to provide this answer. But you should know in certain circumstance you can use a dot ".
" notation even it is a primary. This solution only works for functions that can be access from globals()
:
import functools
class Composable:
def __init__(self, func):
self.func = func
functools.update_wrapper(self, func)
def __getattr__(self, othername):
other = globals()[othername]
return lambda *args, **kw: self.func(other.func(*args, **kw))
def __call__(self, *args, **kw):
return self.func(*args, **kw)
To test:
@Composable
def add1(x):
return x + 1
@Composable
def add2(x):
return x + 2
print((add1.add2)(5))
# 8