interesting bound-built-in-method technique

Michael Hudson mwh21 at cam.ac.uk
Thu Jan 18 13:21:01 EST 2001


Chris Ryland <cpr at emsoftware.com> writes:

> 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.

Not exactly common, but I've done things like this before - bound
methods rock :-)

> Are there other clever but generally obscure idia? (Idioms? ;-)

Probably hundreds, although no examples spring to mind (almost by
definition!).  But bear in mind that the more obscure an idiom is, the
less likely it is to be a good idea.

Python code that I've just thrown together quickly sometimes ends
containing alarmingly hairy code, but I can't find any just now (and I
wouldn't recommand emulating it if I could!).

Ooh, here's one bit:

def disp_str(buffer):
    s = map(_my_unctrl, buffer)
    return (''.join(s),
            map(ord, ''.join(map(lambda x:'\001'+(len(x)-1)*'\000', s))))

The irritating thing about this code is that I can't think of a
quicker way to rewrite it (it's called in a hotspot) other than
writing it in C...

Cheers,
M.

-- 
  Indeed, when I design my killer language, the identifiers "foo" and
  "bar" will be reserved words, never used, and not even mentioned in
  the reference manual. Any program using one will simply dump core
  without comment. Multitudes will rejoice. -- Tim Peters, 29 Apr 1998



More information about the Python-list mailing list