How to raise exception if None value encountered in dict?
Solution 1
You're getting a SyntaxError
because raise
is a statement not an expression, so the or raise KeyError
part doesn't make [syntactic] sense. One workaround is to put just that into a function like the following, which is only called if the looked-up value is something non-True, like None
, 0
, ''
, and []
.
Caveat: Note that doing this is potentially confusing since what it effectively does is make the presence of any of those types of values appear to be as though the protocol
key wasn't there even though technically it was...so you might want to consider deriving your own specialized exception class from one of the built-ins and then deal with those instead of (ab)using what KeyError
normally means.
def raise_KeyError(msg=''): raise KeyError(msg) # Doesn't return anything.
try:
protocol = serverInfo_D['protocol'] or raise_KeyError('protocol not present')
except KeyError:
print('Improper server config!')
Solution 2
If you want it in one line you could always make a function:
def valueOrRaise(data, key):
value = data.get(key)
if value is None:
raise KeyError("%s not present" % key)
return value
try:
protocol = valueOrRaise(serverInfo_D, 'protocol')
except KeyError:
print "server config is not proper"
Solution 3
Why do you want to have an exception, if you're really using it like this? Just use .get()
and check for None
.
protocol = serverInfo_D.get('protocol')
if protocol is None:
print "server config is not proper"
Solution 4
The try
and except KeyError
combination should work. What is not working for you?
And since this in continuation of your previous question, that was not working because you were using dict.get
, which never throws up KeyError
.
However, the code in this question will. And you don't need or raise KeyError
.
>>> d = dict(a=1, b=2)
>>> d.get('c') # no KeyError
>>> d['c'] # KeyError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'c'
goutham
Updated on July 23, 2022Comments
-
goutham almost 2 years
I want to raise a
KeyError
exception if the value returned isNone
, but the following throws aSyntaxError: invalid syntax
exception.try: protocol = serverInfo_D['protocol'] or raise KeyError("protocol not present") except KeyError: print "Improper server config"
What's a simple way to get this working?
-
goutham over 13 yearscan't we use or and put it in a single line.. coz I have lot of such validations.
-
goutham over 13 yearswhat if d['c'] contains a None value?
-
martineau over 13 yearsThe
or raise KeyError
part of the OP's code is aSyntaxError
becauseraise
is a statement not an expression. -
PaulMcG over 13 yearsNot quite what the OP asked - the value is present, so it won't raise the KeyError, but it has a None value, which the OP wants to be an exception case.
-
BasedRebel over 13 yearsI think this addresses a different problem; he assumes that if the specified protocol is not handled then serverInfo_D['protocol'] is not set, thus assigning from it throws a KeyError. Your code seems to assume that it is set to None, thus a KeyError must be thrown manually.
-
user225312 over 13 years@martineua, @McGuire: If you check out the question the OP asked before this, it makes my point clear as to what I am trying to say. I answered that so I was basing this on that. I maybe wrong, but I think the OP was confusing the answer to previous question and that is what I wanted to clarify. If it wrong, let me know and I will edit/ delete it accordingly.
-
Ivan Castellanos about 5 yearsis so dumb that raise is not an expression in python 3, is like they didn't learn nothing from the print fiasco
-
Ivan Castellanos about 5 yearsBecause some programs need to crash if the key doesn't exist because it means something went terribly wrong and letting the program continue will just cause unpredictable behavior.