dict.get() - default arg evaluated even upon success

后端 未结 6 2001
有刺的猬
有刺的猬 2020-12-05 18:08

Why is the default in dict.get(key[, default]) evaluated even if the key is in the dictionary?

>>> key = \'foo\'
>>> a={}
>>> b={k         


        
相关标签:
6条回答
  • 2020-12-05 18:22

    As in any function call, the arguments are evaluated before the call is executed.
    In this case dict.get() is no exception...

    0 讨论(0)
  • Because you are evaluating it, then passing it as an argument to get. This happens whether or not get ends up using the argument.

    0 讨论(0)
  • 2020-12-05 18:31

    To avoid the lookup you could:

    value = b.get(key)
    if value is None:
       value = a[key]
    

    Or if None is allowed then:

    not_set = object()
    # ...
    value = b.get(key, not_set)
    if value is not_set:
       value = a[key]
    
    0 讨论(0)
  • 2020-12-05 18:32

    You can rewrite the example you gave as

    b.get(key, a.get(key))
    

    to avoid the exception. This will return None if the key is in neither dictionary. More generally, if you want to avoid the evaluation of the second argument, you could use

    try:
        x = b[key]
    except KeyError:
        x = a[key]   # or whatever the default value is supposed to be
    
    0 讨论(0)
  • 2020-12-05 18:33
    1. a[key] is a['foo'] and you don't have that key in a.
    2. this is evaluated before calling b.get hence the error
    3. "even if the key is in the dictionary" - that's anot true, b is empty (but as the 2. points shows, this is not relevant)
    0 讨论(0)
  • 2020-12-05 18:41

    use this instead

    x = b.get(key) or a.get(key)
    

    or and and are short circuit operators, so if b has the key it won't look at a. But problems will arise if you have falsy values in b. If that is the case you can do:

    x = b[key] if key in b else a.get(key)
    
    0 讨论(0)
提交回复
热议问题