[Python-ideas] Dart-like method cascading operator in Python

Masklinn masklinn at masklinn.net
Thu Nov 21 14:34:11 CET 2013


On 2013-11-21, at 13:40 , Nick Coghlan <ncoghlan at gmail.com> wrote:

> On 21 November 2013 20:55, Perešíni Peter <ppershing at gmail.com> wrote:
>> gnuplot.newPlot()
>> ..set("xrange [0:5]")
>> ..set("yrange [0:20]")
>> ..newPlot()
>>     ..addSeries("Linear", [1,2,3])
>>     ..addSeries("Quadratic", [1,4,6])
>> ..run()
> 
> If you just want structural grouping of some code, you can already
> define an appropriate context manager:
> 
> @contextlib.contextmanager
> def value(x)
>    yield x
> 
> with value(gnuplot.newPlot()) as p:
>    p.set("xrange [0:5]")
>    p.set("yrange [0:20]")
>    with value(p.newPlot()) as n:
>        n.addSeries("Linear", [1,2,3])
>        n.addSeries("Quadratic", [1,4,6])
>    p.run()
> 
> It doesn’t define a new scope

And it requires naming things.

An other drawback is that it is a statement, where the cascading
operator yields an expression (at least in Smalltalk it did) (well of
course more or less everything was an expression in smalltalk so that
helped).

I really liked message cascading when I played with it in Smalltalk, but:

1. I find Dart’s cascading syntax rather noisy, and examples on The
   Internets seem to show it regularly used in single-line expression
   which I find a detriment to readability:

       document.body.children.add(new ButtonElement()..id='awesome'..text='Click Me!’;);

2. Unless I missed it, the original suggestion failed to specify what
   the overall expression returns. In Smalltalk, it returns the value of
   the last message of the cascade, and Smalltalk has a `yourself` message
   which returns, well, its self. IIRC, Python has no such message “built
   in”. 

3. It encourages and facilitates APIs based on object mutation and
   incompletely initialised objects, the former being a slight dislike and
   the latter being something I loathe.

4. I doubt OP’s (a) would be fixed, it’s not an issue of attribute deref, so
   a cascading operator would have the exact same behaviour.



More information about the Python-ideas mailing list