[Python-ideas] Dart-like method cascading operator in Python
ppershing at gmail.com
Thu Nov 21 11:55:46 CET 2013
Recently I fell in love with Dart method cascading operator .. to the
degree that I find it really convenient and I am missing it in the Python.
The cascade operator
is the syntactic sugar equivalent of the following:
tmp = myObj
This can be used to greatly simplify instantiating objects and can also
enable creating domain specific languages in Python. In particular, we can
make this much more powerful in Python (as opposed to Dart) because Python
recognizes scope by indentation and therefore it would be possible to do
template = HtmlTemplate()
..paragraph("I am the first paragraph")
..paragraph("I am the second paragraph")
Note that this is strictly better than method chaining, e.g.
template = MyObject().setX(1).setY(2)
a) method chaining is hard to write on multiple lines, the only two options
template = MyObject() \
which is fragile (explicit line continuation is discouraged in Python) or
(template = MyObject()
which looks weird.
b) method chaining cannot take advantage of multiple scoping, e.g. the only
way to write Gnuplot example is
with added method *endPlot()* to the Plot class. Moreover, Plot class now
needs a direct reference to its parent (e.g. Gnuplot) so it can return its
This adds unnecessary cyclic dependencies.
c) method chaining needs specialized API, e.g. each method needs to return
d) method chaining cannot be used with attributes, e.g. there is no
obj = MyObject()
Note that this proposal is different from "in" statement [
in the sense that this proposal does not bring anything new into the scope,
..x = y
tmp1 = obj1
tmp2 = obj2
tmp2.x = y
obj1.obj2.x = y
no matter if obj2 or obj1 contains variable y.
In my opinion, such cascading operator would greatly help creating domain
specific languages APIs in Python which are
1) easily readable. It is better than being lost in a repetitive stream of
lines looking like obj.x(), obj.y(), obj.z(). Note that repetitive stream
of lines (apart from being too verbose) also introduces a possibility of
mistyping the name of the object
2) easy to implement (no special API considerations as returning self from
each function call)
What do you think?
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas