在 python3 中为此方法引发异常,该方法使用默认值检查 dictionary.get?

Raise an exception in python3 for this method which check dictionary.get with default value?

我有一个要求,我必须在方法 "meth(a)" 中引发异常,我唯一能实现的方法是将字典 "a" 声明为某个值,使得 a.get('v', 0) 引发异常

def meth(a):
    if isinstance(a, dict):
        return a.get('v', 0)# I have to raise an exception from here
    return 0

a = {} #I have to give some value into this dictionary so that my meth(a) raises an exception'''
import re
import sys
import traceback

try:
    meth(a)
except Exception:
    print("meth exception!")
    sys.exit()
    raise
else:
    sys.stderr.write("meth has no exception")

取决于您所说的 将字典 "a" 声明为某个值 的意思。您可以创建自己的继承自 dict 的 class,以便 isinstance 测试有效并实施不友好的 get.

class MyDict(dict):

    def get(self, name, default=None):
        raise NameError("No way am I getting you a value. "
            "What kind of a dict do you think I am?")

a = MyDict()

剩下的只是您的程序...