gpt4 book ai didi

python - 断言方法在生产中是否可以接受?

转载 作者:太空宇宙 更新时间:2023-11-03 10:54:53 25 4
gpt4 key购买 nike

在工作中,我遇到了这个方法,它困扰着我。事实上,方法的名称、文档和实现并没有真正相互适应(并且传递 true 使 true 的条件变为 false),我不明白有这样一个方法的意义(这是生产代码):

# @brief An utility method that raises if the singleton is not in a good
# state
#@param expect_instanciated bool : if True we expect that the class is
# allready instanciated, else not
# @throw RuntimeError
@classmethod
def singleton_assert(cls, expect_instanciated=False):
if expect_instanciated:
if not cls.started():
raise RuntimeError("The Settings class is not started yet")
else:
if cls.started():
raise RuntimeError("The Settings class is already started")

这是我的担忧:

  • 这个“断言”函数并没有告诉我太多...并且会让客户认为它总是返回一个 bool 值。
  • “None”是没有意义的,没有信息提供给客户,永远不会。客户端无法保存或传递该信息,或者不得不写几行来简单地设置一个 bool 变量;
  • 我认为当方法无法正常工作时应该抛出异常,以应对意外行为。很明显!
  • 此方法限制客户端处理他可能不关心的异常,并且在不使用 try..catch block 的情况下不给他自己的选择,这对我来说似乎不太好;
  • 那些引发的异常似乎假装是一个正常的返回值,就像“file_exists()”方法在没有文件时引发异常,有文件时则没有;
  • 对我来说,在生产中保留这种方法意味着我对代码的稳定性或设计没有信心。单例实例不应超过一个。例如,python 的 exists() 方法不是一个断言,并且总是返回一个 bool 值!我看不出有任何理由让这种方法按原样投入生产(实际上应该删除,或移至单元测试套件)。

我非常确信这种方法是错误的。然而,知道这个特定代码是否正确是一回事,知道以更一般的方式是否会是这种情况是另一回事。因此:

断言方法可以投入生产吗?

编辑:正如评论员所指出的,这是一种相当常见的断言方法(在 python 核心代码中)。

但是,针对此类方法进行更深入的研究,我严格按照“单元测试”或“调试”上下文运行,有些人声称不应将其插入生产。如果它是在测试/调试环境中,我就不会在这篇文章中窃听。

因此:关于让 assert 方法在生产环境中滑动的可行性是否有更多说明?

编辑 2:When should assertions stay in production code?这是我在谷歌搜索时发起的仅有的演讲之一。我还不清楚。

最佳答案

这个方法很好。

this "assert" function doesn't tell me much... And would let the client think it will always return a boolean.

assert 是许多语言中的常用习语。目的是检查预期始终为真的条件。失败的断言表示存在编码错误。因此,该方法通常不返回任何内容,如果条件失败则抛出异常。

"None" is meaningless, no information provided to the client, never. The client can't save or pass that information, or would have to write few lines to simply set a boolean variable ;

无需检查断言的结果。

I think exceptions ought to be thrown when the method can't do its work properly, for unexpected behavior. Here it does, clearly !

断言应该在 100% 的时间内通过。仅当条件意外失败时才会抛出异常。

this method is constraining the client to handle an exception he may not care about, and doesn't give him it's own choice without using a try..catch block, and this seems not fine to me ;

决不应该处理断言异常。它们表示编码错误。不期望程序应该从错误中恢复。通常最好只是崩溃。

我正在区分 错误 和其他异常情况。像找不到文件这样的 I/O 错误是您需要计划的用户或系统错误。您应该捕获这些异常并从中恢复。空指针异常或断言错误是错误的迹象。您无法从它们中恢复过来,因为当它们发生时谁知道还有什么可能出了问题?错误需要修复,而不是处理。

However, doing deeper researchers target at this type of method, I strictly ran upon "unit testing" or "debugging" context, with some claiming that it should not be pushed into production. I wouldn't have bugged on this piece if it was in a testing/debugging context.

在生产代码中运行断言没有错。它们没有害处,也不是糟糕的设计。事实上,它们是很好的设计。他们确认系统运行正常。

人们有时在生产代码中禁用断言的原因是为了性能。他们不想要额外检查的开销。就个人而言,我不参与任何对性能敏感的程序,因此我始终保持断言处于启用状态。额外的安全性非常值得一些 if 检查的成本可以忽略不计。

关于python - 断言方法在生产中是否可以接受?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42837054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com