How to raise exception if None value encountered in dict?
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!')
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"