Callable as the default argument to dict.get without it being called if the key exists

后端 未结 5 836
一向
一向 2021-01-04 05:50

I am trying to provide a function as the default argument for the dictionary\'s get function, like this

def run():
   print \"RUNNING\"

test = {\'store\':1         


        
5条回答
  •  执笔经年
    2021-01-04 06:06

    I suppose you want to have the callable applied only if the key does not exist.

    There are several approaches to do so. One would be to use a defaultdict, which calls run() if key is missing.

    from collections import defaultdict
    def run():
       print "RUNNING"
    
    test = {'store':1}
    test.get('store', run())
    
    test = defaultdict(run, store=1) # provides a value for store
    test['store'] # gets 1
    test['runthatstuff'] # gets None
    

    Another, rather ugly one, one would be to only save callables in the dict which return the apropriate value.

    test = {'store': lambda:1}
    test.get('store', run)() # -> 1
    test.get('runrun', run)() # -> None, prints "RUNNING".
    

    If you want to have the return value depend on the missing key, you have to subclass defaultdict:

    class mydefaultdict(defaultdict):
        def __missing__(self, key):
            val = self[key] = self.default_factory(key)
            return val
    
    d = mydefaultdict(lambda k: k*k)
    d[10] # yields 100
    
    @mydefaultdict # decorators are fine
    def d2(key):
        return -key
    d2[5] # yields -5
    

    And if you want not to add this value to the dict for the next call, you have a

    def __missing__(self, key): return self.default_factory(key)
    

    instead which calls the default factory every time a key: value pair was not explicitly added.

提交回复
热议问题