[Python-ideas] Anonymous blocks (again):

Terry Jan Reedy tjreedy at udel.edu
Tue May 14 17:22:49 CEST 2013


On 5/14/2013 8:45 AM, Joao S. O. Bueno wrote:
> 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

None val should not always be converted to self. Consider [None].pop(), 
where None is the real return, not a placeholder for no return.

> Which allows, for example:
>
>>>> a = []
>>>> Chain(a).append(5).append(6).append(-1).sort().append(3)

Which either raises or does the wrong thing for list.pop

> <__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.




More information about the Python-ideas mailing list