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

后端 未结 5 857
一向
一向 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条回答
  •  萌比男神i
    2021-01-04 06:08

    See the discussion in the answers and comments of dict.get() method returns a pointer. You have to break it into two steps.

    Your options are:

    1. Use a defaultdict with the callable if you always want that value as the default, and want to store it in the dict.

    2. Use a conditional expression:

      item = test['store'] if 'store' in test else run()
      
    3. Use try / except:

      try:
          item = test['store']
      except KeyError:
          item = run()
      
    4. Use get:

      item = test.get('store')
      if item is None:
          item = run()
      

    And variations on those themes.

    glglgl shows a way to subclass defaultdict, you can also just subclass dict for some situations:

    def run():
        print "RUNNING"
        return 1
    
    class dict_nokeyerror(dict):
        def __missing__(self, key):
            return run()
    
    test = dict_nokeyerror()
    
    print test['a']
    # RUNNING
    # 1
    

    Subclassing only really makes sense if you always want the dict to have some nonstandard behavior; if you generally want it to behave like a normal dict and just want a lazy get in one place, use one of my methods 2-4.

提交回复
热议问题