[Python-ideas] Anonymous blocks (again):

Joao S. O. Bueno jsbueno at python.org.br
Tue May 14 14:45:28 CEST 2013


On 13 May 2013 22:55, Haoyi Li <haoyi.sg at gmail.com> wrote:
> I do not think expression soup is particularly bad, it's just Javascript's
> implementation (as usual) that is pretty borked. In Scala, expression
> chaining lets you do some pretty nice things:
>
>
>
>       memory.take(freePointer)
>
>             .grouped(10)
>
>             .map(_.fold("")(_+"\t"+_))
>
>             .reduce(_+"\n"+_)
>


I hope you know that if you enjoy this style,
Python _is_ for you, and I consider it part of the
"multiparadigm" language.

You just have to design your methods to always return
"self" - or make a class decorator to do so.

But in case you are using other people's classes
an adaptor for methosds that woudl return "None"
is easy to achieve.

I made this example a couple months ago to get it working:

class Chain:
    def __init__(self, obj, root=None):
        self.__obj = obj
    def __getattr__(self, attr):
        val = getattr(self.__obj, attr)
        if callable(val):
            self.__callable = val
            return self
        return val
    def __call__(self, *args, **kw):
        val = self.__callable(*args, **kw)
        if val is None:
            return self
        return val

Which allows, for example:

>>> a = []
>>> Chain(a).append(5).append(6).append(-1).sort().append(3)
<__main__.Chain object at 0x12b6f50>
>>> a
[-1, 5, 6, 3]

And would work in your example as well, should you have a class with
the desired methods.


  js
 -><-


More information about the Python-ideas mailing list