Python:我不允许引发异常。还有其他优雅的Python方式吗?

发布于 2024-09-26 06:07:51 字数 558 浏览 6 评论 0 原文

我的工作场所规定了不得使用异常的规则(允许捕捉)。如果我有这样的代码,

def f1()
 if bad_thing_happen():
   raise Exception('bad stuff')
 ...
 return something

我可以将其更改为

def f1()
  if bad_thing_happen():
    return [-1, None]
  ...
  return [0, something]

f1 调用者会像这样

def f1_caller():
  code, result = f1(param1)
  if code < 0:
    return code
  actual_work1()
  # call f1 again
  code, result = f1(param2)
  if code < 0:
    return code
  actual_work2()
  ...

Python 中还有比这更优雅的方法吗?

My work place has imposed a rules for no use of exception (catching is allowed). If I have code like this

def f1()
 if bad_thing_happen():
   raise Exception('bad stuff')
 ...
 return something

I could change it to

def f1()
  if bad_thing_happen():
    return [-1, None]
  ...
  return [0, something]

f1 caller would be like this

def f1_caller():
  code, result = f1(param1)
  if code < 0:
    return code
  actual_work1()
  # call f1 again
  code, result = f1(param2)
  if code < 0:
    return code
  actual_work2()
  ...

Are there more elegant ways than this in Python ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

格子衫的從容 2024-10-03 06:07:52

Python 中的异常是不可避免的,并且通常是解决问题的直接方法。此外,异常还携带大量信息,可以帮助快速定位(通过堆栈跟踪)和识别问题(通过异常类或消息)。

无论谁提出这个一揽子政策,肯定会想到另一种语言(也许是 C++?),在这种语言中,抛出异常是一种更昂贵的操作(如果您的代码在 20 年前的计算机上执行,则会降低性能)。

回答您的问题:另一种方法是返回错误代码。这意味着您将函数结果与错误处理混合在一起,这会引发(哈!)它自己的问题。然而,返回 None 通常是指示函数失败的完全合理的方式。

Exceptions in python are not something to be avoided, and are often a straightforward way to solve problems. Additionally, an exception carries a great deal of information with it that can help quickly locate (via stack trace) and identify problems (via exception class or message).

Whoever has come up with this blanket policy was surely thinking of another language (perhaps C++?) where throwing exceptions is a more expensive operation (and will reduce performance if your code is executing on a 20 year old computer).

To answer your question: the alternative is to return an error code. This means that you are mixing function results with error handling, which raises (ha!) it's own problems. However, returning None is often a perfectly reasonable way to indicate function failure.

眼藏柔 2024-10-03 06:07:52

返回 None 相当常见,并且从概念上讲效果很好。如果您期望返回值,但没有得到任何返回值,则表明出现了问题。

如果您希望返回列表(或字典等),另一种可能的方法是返回列表或字典。这可以很容易地使用 if 进行测试,因为在 Python 中空容器的计算结果为 False,如果您要迭代它,您甚至可能不需要检查对于它(取决于如果函数失败你想做什么)。

当然,这些方法不会告诉您函数失败的原因。因此,您可以返回一个异常实例,例如return ValueError("invalid index")。然后,您可以使用 isinstance() 测试特定异常(或一般异常)并打印它们以获得正确的错误消息。 (或者您可以提供一个辅助函数来测试返回代码以查看它是否派生自 Exception。)您仍然可以创建自己的 Exception 子类;您只需归还它们而不是饲养它们。

最后,我将努力改变这个荒谬的政策,因为异常是 Python 工作方式的重要组成部分,开销很低,并且任何使用你的函数的人都会期望异常。

Returning None is reasonably common and works well conceptually. If you are expecting a return value, and you get none, that is a good indication that something went wrong.

Another possible approach, if you are expecting to return a list (or dictionary, etc.) is to return an empty list or dict. This can easily be tested for using if, because an empty container evaluates to False in Python, and if you are going to iterate over it, you may not even need to check for it (depending on what you want to do if the function fails).

Of course, these approaches don't tell you why the function failed. So you could return an exception instance, such as return ValueError("invalid index"). Then you can test for particular exceptions (or Exceptions in general) using isinstance() and print them to get decent error messages. (Or you could provide a helper function that tests a return code to see if it's derived from Exception.) You can still create your own Exception subclasses; you would simply be returning them rather than raising them.

Finally, I would work toward getting this ridiculous policy changed, as exceptions are an important part of how Python works, have low overhead, and will be expected by anyone using your functions.

浅浅淡淡 2024-10-03 06:07:52

您必须使用返回代码。其他替代方案将涉及可变全局状态(例如 C 的 errno)或传入可变对象(例如列表),但在 Python 中您几乎总是希望避免这两种情况。也许您可以尝试向他们解释 异常如何让您编写更好的后置条件 不是增加返回值的复杂性,而是在其他方面是等效的。

You have to use return codes. Other alternatives would involve mutable global state (think C's errno) or passing in a mutable object (such as a list), but you almost always want to avoid both in Python. Perhaps you could try explaining to them how exceptions let you write better post-conditions instead of adding complication to return values, but are otherwise equivalent.

演多会厌 2024-10-03 06:07:52

不是答案,而是您遇到的所有“不”背后的概念。

根据语言处理错误的方式,有两种类型的语言:

  1. 三思而后行(称为 LBYL)
  2. (称为作为 EAFP)

这是一些文章,但你可以进一步谷歌搜索python lbyl vs eafp:)

Not an answer, but the concept behind all the 'no's you're having.

There are 2 types of languages, based on how they handle the errors:

  1. Look before you leap (known as LBYL)
  2. (known as EAFP)

Here is some article, but you can go further googling python lbyl vs eafp :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文