我喜欢避免“三思而后行”的范例,因为我重视易读的代码。在某些情况下,我无法预测是否会发生错误,比如资源可用性或内存不足的错误。我还没有找到一种干净的编写重复或冗长的代码来处理这些情况的方法。
下面的例子稍微容易理解,但是重复的代码是不可接受的。
为了去除重复代码,我必须添加几行代码并缩进所有内容,这会降低可读性。
有没有一种更短的Python写法,不需要重复代码?
下面的例子稍微容易理解,但是重复的代码是不可接受的。
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
为了去除重复代码,我必须添加几行代码并缩进所有内容,这会降低可读性。
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
有没有一种更短的Python写法,不需要重复代码?