9

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?

3
  • I assume that by "crushes" you mean "crashes"? And by "crashes" I assume you mean "throws an exception"? Also, if I run the exact code you posted, it works just fine. Commented Feb 17, 2010 at 9:17
  • 1
    I fail to see how f4() isn't working as designed. Perhaps you have mistaken expectations. Commented Feb 17, 2010 at 9:18
  • Thanks, Ignacio. I've made a really stupid mistake. Commented Feb 17, 2010 at 9:28

1 Answer 1

9

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.