如何优雅地产生自定义断言错误?

2024-06-16 09:45:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了一堆函数来控制基于消息的仪器。我知道如何使用它们,但是这些函数应该是绝对可靠的,以防在我死后有人想用它来编写代码。下面是一个示例函数:

def AutoRange(self, Function, Source, Value):
    """Enable or disable the instrument autoranging feature.\n
    :Function: "source" or "measure".
    :Source: "v" or "i".
    :Value: 0 or 1."""

    # <Something goes here to check if the inputs are valid>
    self.WRITE("smua.%s.autorange%s = %s" %(Function, Source, Value))

为了满足输入要求,我最初在开头添加了一个RaiseException,但方式很难看:

^{pr2}$

在阅读了assert()之后,我将if替换为:

    MyErrorMessage = "/!\ Error in Keithley.Autorange(): Input not allowed."
    assert (Function in ("source", "measure")), MyErrorMessage
    assert (Source in ("v", "i")), MyErrorMessage
    assert (Value in (0, 1)), MyErrorMessage

一个可能更简洁的变体是:

    ValidInputs = (    Function in ("source", "measure")
                   and Source in ("v", "i")
                   and Value in (0, 1))

    assert (ValidInputs), "/!\ Error in Keithley.Autorange(): Input not allowed."

第二个选项现在更好了,因为我可以明确地知道哪个输入是无效的。所以我的问题是:这就是您应该如何处理断言吗?1个输入1个assert()?如果不是,那么什么是建议的结构?提前谢谢。在


Tags: orthe函数inselfsourceifvalue
1条回答
网友
1楼 · 发布于 2024-06-16 09:45:04

为什么不做Python所做的事情呢?在

我们来看一个例子:

open("foo", "q")
# => ValueError: invalid mode: 'q'

open在C中,但是您可以看到它在例如^{}中的样子:

^{pr2}$

不要害怕让代码再长一点;在Python中不能真正避免它。还有,“错误基思利。自动范围():不允许输入。“不告诉程序员哪个输入不允许。在这种情况下,明确和清晰胜过聪明和简短。在

我会这样做:

def auto_range(self, function, source, value):
    if function not in ["source", "measure"]:
        raise ValueError("Invalid function: %s" % function)
    if source not in ["v", "i"]:
        raise ValueError("Invalid source: %s" % source)
    if value not in [0, 1]:
        raise ValueError("Invalid value: %d" % value)
    # ...

与您的问题没有直接关系,但是最好坚持语言的编码风格:在Python中,变量是snake_case(小写加下划线)。在

相关问题 更多 >