python - Multiple Try/Except blocks -


i have multiple try/except blocks in program analyzing dictionary input module. use try/except (eafp) check if key in input (otherwise, want raise error).

i wondering if there more general approach. instead of

try:     xyz = a['some_key'] except:     print_error("key 'some_key' not defined") 

dozens of times, if there way like

try:     xyz = a['some_key']     xyz2 = a['some_key2']     ... except:     print_error("the key(s) not included some_key, some_key2") 

borked_keys = set() key in list_of_keys_needed:     try:        xyz = a[key]     except keyerror:        borked_keys.add(key)  #python3 variant print("the following keys missing:", ",".join(borked_keys)) #or, suggested jonrsharpe if borked_keys: raise keyerror(",".join(str(i) in borked_keys))  #python 2 variant print "the following keys missing: " + ",".join(borked_keys) #or  if borked_keys: raise keyerror ",".join(str(i) in borked_keys)  #if keys strings, can use ",".join(borked_keys). 

Comments

Popular posts from this blog

java - Andrioid studio start fail: Fatal error initializing 'null' -

android - Gradle sync Error:Configuration with name 'default' not found -

StringGrid issue in Delphi XE8 firemonkey mobile app -