Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raise exception in python dict.get()

actually, I already know what I want to do is kind of strange, but I think it will fit good in my code, so I'm asking:

is there a way to do something like this:

foo = { 'a':1, 'b':2, 'c':3 }
bar = { 'd':4, 'f':5, 'g':6 }

foo.get('h', bar.get('h'))

raising an exception instead of None, in case dict.get() 'fails'?

foo.get('h', bar.get('h', raise)) will raise SyntaxError

foo.get('h', bar.get('h', Exception)) will just return Exception

for now i'm just working around with if not foo.get('h', bar.get('h')): raise Exception but if there is a way to raise directly in the dict.get() I'd be very glad.

Thank you

like image 778
lupodellasleppa Avatar asked Jul 10 '26 01:07

lupodellasleppa


1 Answers

Using subscripts, this is the default behaviour:

d={}
d['unknown key'] --> Raises a KeyError

If you then want to throw a custom exception, you could do this:

try:
    d['unknown key']
except KeyError:
    raise CustomException('Custom message')

And to include the stacktrace from the KeyError:

try:
    d['unknown key']
except KeyError as e:
    raise CustomException('Custom message') from e
like image 198
thom747 Avatar answered Jul 11 '26 15:07

thom747



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!