标签归档:principles

Python中的EAFP原理是什么?

问题:Python中的EAFP原理是什么?

Python中的“使用EAFP原理”是什么意思?你能提供一些例子吗?

What is meant by “using the EAFP principle” in Python? Could you provide any examples?


回答 0

词汇表中

寻求宽恕比允许容易。这种通用的Python编码风格假设存在有效的键或属性,并且在假设被证明为假的情况下捕获异常。这种干净快捷的样式的特点是存在许多tryexcept声明。该技术与C等其他许多语言通用的LBYL风格形成对比。

一个示例是尝试访问字典键。

EAFP:

try:
    x = my_dict["key"]
except KeyError:
    # handle missing key

LBYL:

if "key" in my_dict:
    x = my_dict["key"]
else:
    # handle missing key

LBYL版本必须在字典中搜索关键字两次,并且可能还被认为可读性较差。

From the glossary:

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

An example would be an attempt to access a dictionary key.

EAFP:

try:
    x = my_dict["key"]
except KeyError:
    # handle missing key

LBYL:

if "key" in my_dict:
    x = my_dict["key"]
else:
    # handle missing key

The LBYL version has to search the key inside the dictionary twice, and might also be considered slightly less readable.


回答 1

我将尝试通过另一个示例对其进行解释。

在这里,我们尝试访问文件并在控制台中打印内容。

LBYL-飞跃前先看看:

我们可能要检查是否可以访问该文件,如果可以,我们将其打开并打印内容。如果我们无法访问该文件,我们将发挥else作用。之所以成为竞争条件,是因为我们首先进行访问检查。到我们到达的时候with open(my_file) as f:,由于某些权限问题(例如,另一个进程获得了独占文件锁定),我们可能无法再访问它。该代码可能会引发错误,并且由于我们认为可以访问该文件,因此无法捕获该错误。

import os

my_file = "/path/to/my/file.txt"

# Race condition
if os.access(my_file, os.R_OK):
    with open(my_file) as f:
        print(f.read())
else:
    print("File can't be accessed")

EAFP-较宽容更容易寻求宽恕:

在此示例中,我们只是尝试打开文件,如果无法打开文件,则会抛出IOError。如果可以,我们将打开文件并打印内容。因此,我们不是在什么,而是在尝试做。如果有效,那就太好了!如果不是,我们将捕获错误并进行处理。

# # No race condition
try:
    f = open(my_file)
except IOError as e:
    print("File can't be accessed")
else:
    with f:
        print(f.read())

I’ll try to explain it with another example.

Here we’re trying to access the file and print the contents in console.

LBYL – Look Before You Leap :

We might want to check if we can access the file and if we can, we’ll open it and print the contents. If we can’t access the file we’ll hit the else part. The reason that this is a race condition is because we first make an access-check. By the time we reach with open(my_file) as f: maybe we can’t access it anymore due to some permission issues (for example another process gains an exclusive file lock). This code will likely throw an error and we won’t be able to catch that error because we thought that we could access the file.

import os

my_file = "/path/to/my/file.txt"

# Race condition
if os.access(my_file, os.R_OK):
    with open(my_file) as f:
        print(f.read())
else:
    print("File can't be accessed")

EAFP – Easier to Ask for Forgiveness than Permission :

In this example, we’re just trying to open the file and if we can’t open it, it’ll throw an IOError. If we can, we’ll open the file and print the contents. So instead of asking something we’re trying to do it. If it works, great! If it doesn’t we catch the error and handle it.

# # No race condition
try:
    f = open(my_file)
except IOError as e:
    print("File can't be accessed")
else:
    with f:
        print(f.read())

回答 2

我称之为“乐观编程”。这个想法是,大多数时候人们会做正确的事,错误应该很少。因此,首先编写代码以使“正确的事情”发生,然后,如果没有,则捕获错误。

我的感觉是,如果用户要犯错误,那么他们应该是遭受时间后果的人。正确使用该工具的人会被激怒。

I call it “optimistic programming”. The idea is that most times people will do the right thing, and errors should be few. So code first for the “right thing” to happen, and then catch the errors if they don’t.

My feeling is that if a user is going to be making mistakes, they should be the one to suffer the time consequences. People who use the tool the right way are sped through.