Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #6965

except KeyError, everywhere

Path csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!selfless.tophat.at!newsfeed.xs4all.nl!newsfeed5.news.xs4all.nl!xs4all!post.news.xs4all.nl!not-for-mail
Return-Path <wbsoft@xs4all.nl>
X-Original-To python-list@python.org
Delivered-To python-list@mail.python.org
X-Spam-Status OK 0.000
X-Spam-Evidence '*H*': 1.00; '*S*': 0.00; '(using': 0.05; 'arguments': 0.05; '"""': 0.07; 'received:localnet': 0.07; 'python': 0.08; 'argument,': 0.09; 'dict': 0.09; 'func': 0.09; 'to:name:python list': 0.09; 'this:': 0.10; 'def': 0.12; '"""a': 0.16; '"""returns': 0.16; '**kwargs)': 0.16; '**kwargs):': 0.16; '*args,': 0.16; 'associating': 0.16; 'from:addr:xs4all.nl': 0.16; 'gandhi': 0.16; 'header:X-Face:1': 0.16; 'keyerror:': 0.16; 'mahatma': 0.16; 'message-id:@xs4all.nl': 0.16; 'missing,': 0.16; 'received:194.109': 0.16; 'received:194.109.24': 0.16; 'received:82.95': 0.16; 'received:xs4all.nl': 0.16; 'res': 0.16; 'this?': 0.19; 'seems': 0.21; 'objects': 0.23; 'stored': 0.25; 'function': 0.25; 'specified': 0.26; "i'm": 0.27; '"you': 0.29; 'class': 0.29; 'hi,': 0.31; "can't": 0.32; 'to:addr:python-list': 0.33; 'things': 0.33; 'there': 0.35; 'header:User-Agent:1': 0.35; 'itself,': 0.35; 'try:': 0.35; 'using': 0.35; 'charset:us-ascii': 0.36; 'something': 0.37; 'change': 0.37; 'could': 0.38; 'but': 0.38; 'skip:s 20': 0.39; 'called': 0.39; 'returned': 0.39; 'to:addr:python.org': 0.39; 'really': 0.40; 'subject:, ': 0.60; 'best': 0.60; 'header:Message-Id:1': 0.62; 'wish': 0.70; 'factory': 0.73; 'dict,': 0.84; 'hook': 0.84; 'lookup,': 0.84
From Wilbert Berendsen <wbsoft@xs4all.nl>
Organization www.wilbertberendsen.nl
To Python list <python-list@python.org>
Subject except KeyError, everywhere
Date Fri, 3 Jun 2011 22:08:16 +0200
User-Agent KMail/1.13.5 (Linux/2.6.32-29-generic; KDE/4.5.3; i686; ; )
X-Face t;^H#io{wm#(@U57eQ1l1`z]|~Cs]9P>sd3E4B<8>*Y~~_L9CcPWr?UsFx, yR{g|dxr!XU QGj+hj~)XO/o9, 8frDyHojv.QcqQ%jbw{kMXPg)PET9(, #
MIME-Version 1.0
Content-Type text/plain; charset="us-ascii"
Content-Transfer-Encoding 7bit
X-Virus-Scanned by XS4ALL Virus Scanner
X-BeenThere python-list@python.org
X-Mailman-Version 2.1.12
Precedence list
List-Id General discussion list for the Python programming language <python-list.python.org>
List-Unsubscribe <http://mail.python.org/mailman/options/python-list>, <mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive <http://mail.python.org/pipermail/python-list>
List-Post <mailto:python-list@python.org>
List-Help <mailto:python-list-request@python.org?subject=help>
List-Subscribe <http://mail.python.org/mailman/listinfo/python-list>, <mailto:python-list-request@python.org?subject=subscribe>
Newsgroups comp.lang.python
Message-ID <mailman.2437.1307132130.9059.python-list@python.org> (permalink)
Lines 66
NNTP-Posting-Host 82.94.164.166
X-Trace 1307132130 news.xs4all.nl 49180 [::ffff:82.94.164.166]:41449
X-Complaints-To abuse@xs4all.nl
Xref x330-a1.tempe.blueboxinc.net comp.lang.python:6965

Show key headers only | View raw


Hi,

I find myself all over the place associating objects with each other using 
dicts as caches:

something like this:

_cache = {}

def get_something(obj):
    """Returns the frobnicate-plugin for the specified object."""
    try:
        return _cache[obj]
    except KeyError:
        res = _cache[obj] = LargeClass(obj)
        return res


I would like a dict that would do this by itself, so that I could write:

_cache = somelazydict(LargeClass)

def get_something(obj):
    """Returns the frobnicate-plugin for the specified object."""
    return _cache[obj]

or even using the dict directly:

plugin_store = somelazydict(LargeClass)

It seems that I can't use defaultdict for this, because it calls the factory 
function without an argument, where I need to have the key as argument.

So I came up with this (using the __missing__ dict hook since Python 2.5):

class cachedict(dict):
    """A dict, but with a factory function as the first argument.
    
    On lookup, if the key is missing, the function is called with the key as
    argument. The returned value is also stored in the dict.
    
    """
    def __init__(self, func, *args, **kwargs):
        """Creates the dict, with the factory function as the first argument.
        
        All other arguments work just like dict.
        
        """
        dict.__init__(self, *args, **kwargs)
        self.func = func
    
    def __missing__(self, key):
        res = self[key] = self.func(key)
        return res

Are there other peoply using things like this? Is there a solution like this 
in the standard lib that I'm overlooking? Of course 'except KeyError' 
everywhere is not really a big deal...

With best regards,
Wilbert Berendsen

-- 
http://www.wilbertberendsen.nl/
"You must be the change you wish to see in the world."
        -- Mahatma Gandhi

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

except KeyError, everywhere Wilbert Berendsen <wbsoft@xs4all.nl> - 2011-06-03 22:08 +0200
  Re: except KeyError, everywhere Nobody <nobody@nowhere.com> - 2011-06-04 01:02 +0100
    Re: except KeyError, everywhere --> memoization Wilbert Berendsen <wbsoft@xs4all.nl> - 2011-06-05 00:27 +0200
    Re: except KeyError, everywhere "Gabriel Genellina" <gagsl-py2@yahoo.com.ar> - 2011-06-07 00:45 -0300
      Re: except KeyError, everywhere Ben Finney <ben+python@benfinney.id.au> - 2011-06-07 14:08 +1000
  Re: except KeyError, everywhere Ben Finney <ben+python@benfinney.id.au> - 2011-06-04 10:03 +1000
    Re: except KeyError, everywhere Ben Finney <ben+python@benfinney.id.au> - 2011-06-04 10:37 +1000

csiph-web