interesting bound-built-in-method technique

Steve Holden sholden at holdenweb.com
Thu Jan 18 16:47:10 EST 2001


"Chris Ryland" <cpr at emsoftware.com> wrote in message
news:9476k6$d55$1 at nnrp1.deja.com...
> 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? ;-)
> --
Sorry old chap, I don't seem to understand your banter. On *my* system
(ActivePython):

>>> m = {'foo': 1, 'bar': 0}.has_key
>>> m('foo')
1
>>> m('bar')
1

Furthermore:

>>> m = {'spam': 'yes', 'eggs': 'no', 'chips': 'maybe'}
>>> m = m.has_key
>>> m("spam")
1
>>> m("eggs")
1
>>> m("parrot")
0

In other words, it *doesn't* cast lookup functionally.

[... light dawns ...]

Aah, what you meant to write was:

>>> m = {'spam': 'yes', 'eggs': 'no', 'chips': 'maybe'}.get
>>> m('spam')
'yes'
>>> m('eggs')
'no'
>>> print m("Blue Norwegian")
None

In either case, this *is* a very interesting idiom, and one I haven't seen
before.
Even more interesting might be:

>>> m = {'spam': 'yes', 'eggs': 'no', 'chips': 'maybe'}
>>> f = m.get
>>> f('spam')
'yes'
>>> m['parrot'] = 'dead'
>>> f('parrot')
'dead'

... in other words, binding to a method of a mutable object means the bound
method reflects mutations in the bound object. Of course, modifying the name
you used in the first place won't alter anything:

>>> m = {'parrot': "alive"}
>>> f('parrot')
'dead'

It just removes the mutable object reference from the namespace, presumably
meaning you can't change it any more. Neat. But will the reference to its
method be enough to stop Python from garbage collecting it [I have to
believe the answer is 'yes'].

regards
 Steve






More information about the Python-list mailing list