16.11.2014 Views

callback patterns and idioms in Python

callback patterns and idioms in Python

callback patterns and idioms in Python

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Customiz<strong>in</strong>g sort (by key)<br />

mylist.sort(key=str.toupper)<br />

h<strong>and</strong>ily, speedily embodies the DSU pattern:<br />

def DSU_sort(mylist, key):<br />

aux = [ (key(v), j, v)<br />

for j, v <strong>in</strong> enumerate(mylist)]<br />

aux.sort()<br />

mylist[:] = [v for k, j, v <strong>in</strong> aux]<br />

Note that a little "workaround" is needed wrt the<br />

usual "call a method on each object" OO idiom...<br />

6

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!