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


Groups > comp.lang.python > #39660

Re: Question about defaultdict

From Frank Millman <frank@chagford.com>
Subject Re: Question about defaultdict
Date 2013-02-23 13:54 +0200
References <kga4nc$4jm$1@ger.gmane.org> <kga6rk$kc2$1@ger.gmane.org> <kga7ii$rkq$1@ger.gmane.org>
Newsgroups comp.lang.python
Message-ID <mailman.2339.1361620458.2939.python-list@python.org> (permalink)

Show all headers | View raw


On 23/02/2013 13:02, Peter Otten wrote:
> Frank Millman wrote:
>
>> On 23/02/2013 12:13, Frank Millman wrote:
>>> Hi all
>>>
>>> I use a dictionary as a cache, and I thought that I could replace it
>>> with collections.defaultdict, but it does not work the way I expected
>>> (python 3.3.0).
>>   >
>> [...]
>>>
>>> from collections import defaultdict
>>> my_cache = defaultdict(fetch_object)
>>> my_obj = my_cache['a']
>>>
>>> It does not work, because fetch_object() is called without any arguments.
>>
>> Thanks, Chris and Peter. Some nice ideas to choose from :-)
>>
>> Frank
>
> Oh, I overlooked that you are using Python 3. For that there's also
> functools.lru_cache. Example:
>
>>>> from functools import lru_cache
>>>> @lru_cache(maxsize=None)
> ... def fetch_object(id):
> ...     print("fetching #{}".format(id))
> ...     return id*id # bogus example
> ...
>>>> fetch_object(42)
> fetching #42
> 1764
>>>> fetch_object(42)
> 1764
>>>> fetch_object(10)
> fetching #10
> 100
>
>

Interesting.

Thanks, Peter

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


Thread

Re: Question about defaultdict Frank Millman <frank@chagford.com> - 2013-02-23 13:54 +0200

csiph-web