Popular Python recipes tagged "chaining"http://code.activestate.com/recipes/langs/python/tags/chaining/2016-09-01T12:34:17-07:00ActiveState Code RecipesPython method chaining examples (Python)
2016-02-25T19:40:33-08:00Vasudev Ramhttp://code.activestate.com/recipes/users/4173351/http://code.activestate.com/recipes/580616-python-method-chaining-examples/
<p style="color: grey">
Python
recipe 580616
by <a href="/recipes/users/4173351/">Vasudev Ram</a>
(<a href="/recipes/tags/chaining/">chaining</a>, <a href="/recipes/tags/methods/">methods</a>, <a href="/recipes/tags/object/">object</a>, <a href="/recipes/tags/oop/">oop</a>, <a href="/recipes/tags/python/">python</a>).
</p>
<p>This recipe shows a few examples of doing method chaining in Python.</p>
Method chaining or cascading (Python)
2016-09-01T12:34:17-07:00Steven D'Apranohttp://code.activestate.com/recipes/users/4172944/http://code.activestate.com/recipes/578770-method-chaining-or-cascading/
<p style="color: grey">
Python
recipe 578770
by <a href="/recipes/users/4172944/">Steven D'Aprano</a>
(<a href="/recipes/tags/cascade/">cascade</a>, <a href="/recipes/tags/cascading/">cascading</a>, <a href="/recipes/tags/chaining/">chaining</a>, <a href="/recipes/tags/method/">method</a>).
</p>
<p>A frequently missed feature of built-ins like lists and dicts is the ability to chain method calls like this:</p>
<pre class="prettyprint"><code>x = []
x.append(1).append(2).append(3).reverse().append(4)
# x now equals [3, 2, 1, 4]
</code></pre>
<p>Unfortunately this doesn't work, as mutator methods return <code>None</code> rather than <code>self</code>. One possibility is to design your class from the beginning with method chaining in mind, but what do you do with those like the built-ins which aren't?</p>
<p>This is sometimes called <a href="https://en.wikipedia.org/wiki/Method_cascading">method cascading</a>. Here's a proof-of-concept for an adapter class which turns any object into one with methods that can be chained.</p>