interesting bound-built-in-method technique

Quinn Dunkan quinn at chunder.ugcs.caltech.edu
Sat Jan 20 16:44:33 EST 2001


On Thu, 18 Jan 2001 16:46:01 GMT, Chris Ryland <cpr at emsoftware.com> wrote:
>Reading the Quixote sources taught me an interesting little "hack"
>using bound-built-in methods:
>
>>>> m = {'foo': 1, 'bar': 0}.has_key
>>>> m('foo')
>1
>>>> m('bar')
>0
>
>Is this a common idiom in Python? Very clever for turning a dictionary
>lookup into a functional form.
>
>Are there other clever but generally obscure idia? (Idioms? ;-)

I occasionally use the following pattern:

def f(lst):
    r = []
    a = r.append
    a('this' + lst[0])
    a('that' + lst[1])
    ...
    return r

This is just to save typing, of course, but membership tests like [].has_key
are also useful to pass to functions like filter():

keys = ['baz', 'faz']
d = {'phoo': 1,  'bar': 2, 'baz': 10}
valid_keys = filter(d.has_key, keys)

python normally discourages writing little closures, but bound methods work
much more nicely.  Think of it as a bit of free curry :)


And I've also heard them called 'pydioms' :)



More information about the Python-list mailing list