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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With