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

后端 未结 5 865
一向
一向 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:04

    If you only know what the callable is likely to be at he get call site you could subclass dict something like this

        class MyDict(dict):
    
            def get_callable(self,key,func,*args,**kwargs):
                '''Like ordinary get but uses a callable to 
                generate the default value'''
    
                if key not in self:
                    val = func(*args,**kwargs)
                else:
                    val = self[key]
                return val
    

    This can then be used like so:-

         >>> d = MyDict()
         >>> d.get_callable(1,complex,2,3)
         (2+3j)
         >>> d[1] = 2
         >>> d.get_callable(1,complex,2,3)
         2
         >>> def run(): print "run"
         >>> repr(d.get_callable(1,run))
         '2'
         >>> repr(d.get_callable(2,run))
         run
         'None'
    

    This is probably most useful when the callable is expensive to compute.

提交回复
热议问题