Reputation: 153
I have multiple try/except blocks in a program where I am analyzing a dictionary input from another module. I basically use the try/except (EAFP) to check if a certain key is in the input (otherwise, I want to raise an error).
I was wondering if there is a more general approach. Instead of
try:
xyz = a['some_key']
except:
print_error("Key 'some_key' was not defined")
dozens of times, if there was a way to do something like
try:
xyz = a['some_key']
xyz2 = a['some_key2']
...
except:
print_error("The key(s) that were not included were some_key, some_key2")
Upvotes: 1
Views: 425
Reputation: 3334
borked_keys = set()
for key in list_of_keys_needed:
try:
xyz = a[key]
except KeyError:
borked_keys.add(key)
#python3 variant
print("The following keys were missing:", ",".join(borked_keys))
#or, as suggested by jonrsharpe
if borked_keys: raise KeyError(",".join(str(i) for i in borked_keys))
#python 2 variant
print "The following keys were missing: " + ",".join(borked_keys)
#or
if borked_keys: raise KeyError ",".join(str(i) for i in borked_keys)
#if the keys are already strings, you can just use ",".join(borked_keys).
Upvotes: 4