Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!feeds.phibee-telecom.net!newsfeed.xs4all.nl!newsfeed1a.news.xs4all.nl!xs4all!newsgate.cistron.nl!newsgate.news.xs4all.nl!post.news.xs4all.nl!not-for-mail Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.017 X-Spam-Evidence: '*H*': 0.97; '*S*': 0.00; 'argument': 0.05; 'received:134': 0.05; 'def': 0.12; 'dependant': 0.16; 'given)': 0.16; 'key):': 0.16; 'key?': 0.16; 'subject:variable': 0.16; 'typeerror:': 0.16; 'wrote:': 0.18; 'obviously': 0.18; 'header :User-Agent:1': 0.23; 'mon,': 0.24; 'this:': 0.26; 'header:In- Reply-To:1': 0.27; 'chris': 0.29; '"",': 0.31; 'work:': 0.31; 'file': 0.32; 'class': 0.32; '(most': 0.33; 'skip:_ 10': 0.34; 'subject:with': 0.35; 'something': 0.35; 'but': 0.35; 'possible': 0.36; 'should': 0.36; 'implement': 0.38; 'nov': 0.38; 'to:addr :python-list': 0.38; 'pm,': 0.38; 'recent': 0.39; 'skip:. 10': 0.39; 'to:addr:python.org': 0.39; 'how': 0.40; 'default': 0.69; 'hoping': 0.75; 'pardon': 0.84 X-IronPort-Anti-Spam-Filtered: true X-IronPort-Anti-Spam-Result: ArQEACHSWFSGuA9G/2dsb2JhbABchDqDBtMmAoE2AQEBAQGFAAEBBCNVEQsYAgIFFgsCAgkDAgECAUUTBgICiD23HY9ShWEBAQgCIIEtj2oWgmGBVAWTK4pch1yOc4N5awGCSgEBAQ Date: Tue, 04 Nov 2014 14:21:30 +0100 From: Antoon Pardon User-Agent: Mozilla/5.0 (X11; Linux i686; rv:31.0) Gecko/20100101 Icedove/31.0 MIME-Version: 1.0 To: python-list@python.org Subject: Re: Dictionaries with variable default. References: <54576150.6090002@rece.vub.ac.be> In-Reply-To: Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 7bit X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.15 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Newsgroups: comp.lang.python Message-ID: Lines: 30 NNTP-Posting-Host: 2001:888:2000:d::a6 X-Trace: 1415107297 news.xs4all.nl 2862 [2001:888:2000:d::a6]:39314 X-Complaints-To: abuse@xs4all.nl Xref: csiph.com comp.lang.python:80177 Op 03-11-14 om 12:09 schreef Chris Angelico: > On Mon, Nov 3, 2014 at 10:04 PM, Antoon Pardon > wrote: >> Is it possible to have a default dictionary where the default is dependant >> on the key? >> >> I was hoping something like this might work: >>>>> m = defaultdict(lambda key: key+1) >> But it obviously doesn't: >>>>> m[3] >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: () takes exactly 1 argument (0 given) > Yes, but not with the defaultdict. Instead, just implement __missing__: > > class KeyPlusOne(dict): > def __missing__(self, key): return key+1 > > ChrisA So How should I call this: class ...dict(dict): def __init__(self, fun): self.fun = fun def __missing__(self, key): return self.fun(key)