I like to avoid the “watch before jumping” paradigm because I value easy-to-read code. In some cases, I cannot predict whether an error will occur, such as resource availability or memory errors. I have not found a clean way to write code that is repeatable or lengthy to process these scripts.
The following example is minimally readable, but duplicate code is not acceptable.
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
To remove duplicate code, I have to add a few more lines and indents, reducing 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 to write this in Python that doesn't duplicate code?
source
share