Latest recipes tagged "cascading"http://code.activestate.com/recipes/tags/cascading/new/2016-09-01T12:34:17-07:00ActiveState Code RecipesMethod 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>