python - 当异常来源未知时,EAFP 的方式是什么?

标签 python python-3.x

我是 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/

相关文章:

python - 如何在我的自定义小部件模板中包含内置的 django 小部件模板?

python - TypeError : int() argument must be a string or a number, 不是 'Model Instance'

python - 异步函数调用异步生成器调用异步函数

python - python中socket.PF_PACKET和socket.AF_INET的区别

python - 仅替换一定数量的字符

python - 使用就地排序的 QuickSort

python - 迭代页面元素 beautifulsoup

具有代理支持的 python webkit

python - 为什么 Emacs 将我的文字 Unicode 字符串弄错了?

python-3.x - 计算同一组中有多少行在 Pandas DataFrame 中的每一行的给定列中具有较大的值