小编Shi*_*raz的帖子

生产中可以接受断言方法吗?

在工作中,我遇到了这种方法,它困扰着我。事实上,方法的名称、文档和实现并没有真正相互匹配(并且传递 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")
Run Code Online (Sandbox Code Playgroud)

以下是我的担忧:

  • 这个“断言”函数并没有告诉我太多......而且会让客户认为它总是会返回一个布尔值。
  • “无”是没有意义的,没有提供给客户的信息,从不。客户端无法保存或传递该信息,或者必须编写几行来简单地设置一个布尔变量;
  • 我认为当该方法无法正常工作时,应该抛出异常,以应对意外行为。在这里,很明显!
  • 这种方法限制了客户端处理他可能不关心的异常,并且在不使用 try..catch 块的情况下不会给他自己的选择,这对我来说似乎不太好;
  • 那些引发的异常似乎假装是一个正常的返回值,就像“file_exists()”方法在没有文件时引发异常,在没有文件时引发异常; …

python return exception

6
推荐指数
1
解决办法
4293
查看次数

标签 统计

exception ×1

python ×1

return ×1