Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #6984
| From | Ben Finney <ben+python@benfinney.id.au> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: except KeyError, everywhere |
| References | <mailman.2437.1307132130.9059.python-list@python.org> |
| Date | 2011-06-04 10:03 +1000 |
| Message-ID | <87sjrq4g4l.fsf@benfinney.id.au> (permalink) |
| Organization | Unlimited download news at news.astraweb.com |
Wilbert Berendsen <wbsoft@xs4all.nl> writes:
> 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
You seem to be looking for the Memoize pattern
<URL:https://secure.wikimedia.org/wikipedia/en/wiki/Memoization>.
It's best to implement Memoize as a Python decorator in one place
<URL:http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize>.
Once you have that decorator, apply it to any function you like::
@memoized
def get_something(obj):
""" Returns the frobnicate-plugin for the specified object. """
res = LargeClass(obj)
return res
--
\ “Faith may be defined briefly as an illogical belief in the |
`\ occurrence of the improbable.” —Henry L. Mencken |
_o__) |
Ben Finney
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll 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