raghubasireddi raghubasireddi - 3 months ago 10
Python Question

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

I have a requirement that I have to raise an exception in method "meth(a)", only way I can achieve is to declare dictionary "a" to some value such that a.get('v', 0) raise an exception

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

except Exception:
print("meth exception!")
sys.stderr.write("meth has no exception")


Depends on what you mean by declare dictionary "a" to some value. You can create your own class that inherits from dict so that the isinstance test works and implement an unfriendly 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()

and the rest is just your program...