__contains__ vs. __getitem__

Bruno Desthuilliers onurb at xiludom.gro
Thu Aug 10 04:05:23 EDT 2006


David Isaac wrote:
>> Alan Isaac wrote:
>>> I have a subclass of dict where __getitem__ returns None rather than
>>> raising KeyError for missing keys.  (The why of that is not important
> for
>>> this question.)
> 
> "Bruno Desthuilliers" <onurb at xiludom.gro> wrote:
>> Well, actually it may be important... What's so wrong with d.get('key')
>> that you need this behaviour ?
> 
> I want to use the mapping with string interpolation.
> 
Well, this makes sens... But then why not use a plain dict to collect
data, and wrap it in a special one just before using it for
interpolation ? ie:

class MyDictWrapper(object):
  def __init__(self, d, default=None):
    self._d = d
    self._default = default
  def __getitem__(self, key):
    return self._d.get(key, self._default)


def render(d):
  tpl = "%(who)s says '%(say)s' and the %(what)s is %(state)s."
  return tpl % MyDictWrapper(d)

This would avoid any potential trouble with using a strange kind of dict
 in other parts of the code...

My 2 cents...



More information about the Python-list mailing list