a complement function
Tim Hochberg
tim.hochberg at ieee.org
Tue Aug 22 01:56:24 EDT 2000
Brad Knotwell <knotwell at ix.netcom.com> writes:
> Hello all--
>
> I was wondering if there's a clean way to do the following:
>
> def complement(function):
> return lambda x,function=function: not apply(function,x)
>
> print complement(lambda x: x == 1)((1,))
> print complement(lambda x: x == 1)((2,))
> print complement(lambda x,y: x == y)((3,4))
> print complement(lambda x,y: x == y)((4,4))
>
>
> As you can see, it works fine as long as the function is called with
> a tuple representing all arguments. What I'd prefer is the more obvious
> interface:
>
> print complement(lambda x: x == 1)(1)
> print complement(lambda x: x == 1)(2)
> print complement(lambda x,y: x == y)(3,4)
> print complement(lambda x,y: x == y)(4,4)
>
> FWIW, I suppose the real question would ask if there's any way for
> default arguments and variably-sized argument lists to play nicely
> together.
I think your best bet here is to migrate from a real function to a
class pretending it's a function. That tends to be helpful when
default arguments start causing problems. For example:
class complement:
def __init__(self, function):
self.function = function
def __call__(self, *args, **kargs):
return apply(self.function, args, kargs)
print complement(lambda x: x == 1)(1)
print complement(lambda x: x == 1)(2)
print complement(lambda x,y: x == y)(3,4)
print complement(lambda x,y: x == y)(4,4)
Enjoy,
-tim
More information about the Python-list
mailing list