kachayev / fn.py

Functional programming in Python: implementation of missing features to enjoy FP
Other
3.35k stars 204 forks source link

underscore lambda cannot use __contains__ (IOW "in") [renamed issue] #65

Open mjkaye opened 10 years ago

mjkaye commented 10 years ago

I often find myself in the situation where I want to create a filter and, if using the underscore syntax, _ is a sequence. For instance:

    my_filter = F() >> (filter, _[1] in TYPE_MAP)

In this situation, _ will be an item from a dict.items() and will, therefore, be a 2-tuple. I want my_filter to return only the items for which the value (the second item in the 2-tuple) is in TYPE_MAP.

However, when run, the above code results in TypeError: "'bool' object is not callable". It looks as if it's trying to evaluate _[1] in TYPE_MAP at the time of partial function creation, rather than when actually calling the resulting function.

Is there a way to achieve this with the underscore syntax, or do I just have to use the lambda syntax?

Thanks

Digenis commented 10 years ago

__contains__() results are implicitly cast to bool, it can not return a callable to implement this trick. Therefore underscore can not define this method to do what we would want it to mean here. Follow this discussion https://mail.python.org/pipermail/python-ideas/2010-July/007733.html

Look at this:

from operator import contains
from fn import F, _

my_filter = F(filter, F(contains, TYPE_MAP) << _[1])
mjkaye commented 10 years ago

Thanks Digenis. I should have done more testing to find the real reason for the error. I've renamed the issue to reflect the underlying restriction.

Perhaps the documentation could be updated to more clearly explain the limitations of underscore lambdas?