我是 Python 新手,正在尝试了解 Python 方式®
我了解了 EAFP 原则并且喜欢它,但是在这个示例中如何应用它?
编辑:我只关心item没有children属性,而不关心dosomethingwith()内部发生的事情。
根据我对 EAFP 的理解,我应该像平常一样使用可能错误的语句,并捕获异常,但由于该语句位于 for 中,那么我被迫尝试整个 for block 。
try:
for child in item.children:
dosomethingwith( child )
except AttributeError:
""" did the exception come from item.children or from dosomethingwith()? """
不过,做这样的事情看起来很像 LBYL:
try:
item.children
except AttributeError:
""" catch it """
for child in item.children: ...
最佳答案
实际上,当您想要访问可能不可用的资源时,您可以使用 EAFP。 IMO,AttributeError
是一个坏例子......
无论如何,您可以区分缺少的 children
属性和 do_something_with()
函数引发的 AttributeError
。您需要有两个异常处理程序:
try:
children = item.children
except AttributeError:
print("Missing 'children' attribute")
raise # re-raise
else:
for child in children:
try:
do_something_with(child)
except AttributeError:
print("raised from do_something_with()")
raise # re-raise
EAFP 的一个经典示例是 make_dir_if_not_exist()
函数:
# LBYL
if not os.path.exists("folder"):
os.mkdir("folder")
# EAFP
try:
os.mkdir("folder")
except FileExistsError:
pass
关于python - 当异常来源未知时,EAFP 的方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54507074/