Python:如果将默认值设置为抛出异常的函数,则Dict get方法始终抛出异常

时间:2016-03-31 03:17:17

标签: python exception dictionary data-structures default

在get方法中,如果我的默认函数有异常,则控件始终转到默认函数,而不管字典中是否存在键。这是代码块,演示了相同的内容 编译器详细信息如下: Python 2.7.6(默认,2015年4月8日,11:18:18) linux2上的[GCC 4.7.2]

abc = 1
bcd = 2
class a(object):
    def test1(self):
        alphaNumMap = {
                    'a':abc,
                    'b':bcd
                    }
        num = alphaNumMap.get("a", self.add())
        print num


    def add(self):
        print "add called "
        raise Exception

if __name__ == "__main__":
    A = a()
    A.test1()

以上代码的输出如下:

add called 
Traceback (most recent call last):
File "test2.py", line 19, in <module>
A.test1()
File "test2.py", line 10, in test1
ipXpath = alphaNumMap.get("a",self.add())
File "test2.py", line 15, in add
raise Exception 
Exception

虽然预期输出为1,但因为&#39; a&#39;存在于dict alphaNumMap

2 个答案:

答案 0 :(得分:2)

当然它会引发异常。

任何函数调用(在您的情况下,alphaNumMap.get("a",self.add()))必须首先评估其所有参数,在将控制传递给函数之前。因此,调用add(),引发异常,并且根本不会调用get()

最简单的方法是分配一个默认(例外)值,然后检查它:

ipXpath = alphaNumMap.get("a", None) # instead of None there could be
if ipXpath is None:                  # An_exceptional_value_specific_to_your_program
    ipXpath = self.add()

表达式可以更短(一个oneliner),但整个想法保持不变

答案 1 :(得分:1)

.get将首先评估默认值,无论是否找到密钥。要解决此问题,请执行以下操作:x=d.get(key)然后if x is None: do stuff

.get只是恰好属于字典的另一个函数。与python中的任何其他函数一样,在执行函数之前需要计算所有参数。其中一个参数是self.add(),最终会在获得评估时抛出异常。

例如:

>>> d = {1: 2}
# Throws a NameError - fn is undefined
>>> d.get(1, fn())
# Prints 2 (here you need to be careful with the or - anything that evaluates to a False (in a boolean sense) will end up causing fn() to execute - maybe compare to a None, which is what get would have return for a missing key.
>>> d.get(1) or fn() # Careful with the or here, alternative approach below
>>> x = d.get(1)
>>> y = x if x is not None else fn()
相关问题