pythoncnc

Python : simplify try / except code?


Sorry if the title is not explanatory enough, but it's the best I could come up with. This is a part of my code, a python script that translates files from Xilog3 to woodWOP format (cnc programs).

try:
    print >>woodWOPfile, 'YA="%s"' %xbo['Y']
except KeyError:
    xbo['Y']=xbo_prev['Y']
    print >>woodWOPfile, 'YA="%s"' %xbo['Y']

This prints a dictionary key item to the output file. If the key does not exist, I want to load it from the previous version of the dictionary, xbo_prev, which is copied from xbo before every new line reading cycle.

Using the print rule twice seems pretty stupid, but it's the best I can come up with. Is there a way to simplify this?

Thanks :).


Solution

  • You could simply use dict.setdefault:

    print woodWOPfile, 'YA="%s"' % xbo.setdefault('Y', xbo_prev['Y'])
    

    This gets the value corresponding to key Y if it is present in the map, otherwise sets it to the second parameter and returns it.