I like to avoid the "look before you leap" paradigm because I value easy-to-read code. In some cases, I cannot predict whether an error will occur, such as resource availability or out-of-memory errors. I haven't found a clean way of writing code that is repetitious or lengthy to handle these scenarios.
The following example is marginally readable, but duplicate code is unacceptable.
try:
myobject.write(filename)
except OSError:
if prompt("%s is in use by another application." +
"Close that application and try again.") == "Try again":
myobject.write(filename) #repeated code
In order to remove the duplicate code, I must add a few more lines and indent everything, reducing the readability.
success = False
while not success:
try:
myobject.write(filename)
success = True
except OSError:
if prompt("%s is in use by another application." +
"Close that application and try again.") != "Try again":
break
Is there a shorter way of writing this in Python that doesn't duplicate code?