Python function composition

◇◆丶佛笑我妖孽 提交于 2019-12-20 10:44:18

问题


I've tried to implement function composition with nice syntax and here is what I've got:

from functools import partial

class _compfunc(partial):
    def __lshift__(self, y):
        f = lambda *args, **kwargs: self.func(y(*args, **kwargs)) 
        return _compfunc(f)

    def __rshift__(self, y):
        f = lambda *args, **kwargs: y(self.func(*args, **kwargs)) 
        return _compfunc(f)

def composable(f):
    return _compfunc(f)

@composable    
def f1(x):
    return x * 2

@composable
def f2(x):
    return  x + 3

@composable
def f3(x):
    return (-1) * x

print f1(2) #4
print f2(2) #5
print (f1 << f2 << f1)(2) #14
print (f3 >> f2)(2) #1
print (f2 >> f3)(2) #-5

It works fine with integers, but fails on lists/tuples:

@composable
def f4(a):
    a.append(0)

print f4([1, 2]) #None

Where is a mistake?


回答1:


append does in-place addition, as Ignacio Vazquez-Abrams said (well, implied) -- so, while you could fix that by just adding a return to your function, it would have the side-effect of changing the argument it was passed, too:

@composable
def f4(a):
    a.append(0)
    return a

It would be best to use the following even more concise code which also creates and returns a new object:

@composable
def f4(a):
  return a + [0]


来源:https://stackoverflow.com/questions/2279423/python-function-composition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!