为接收到的无效参数值引发异常的最佳实践

2024-04-19 04:49:59 发布

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

每次我写一个有(一个或多个)参数的函数时,我在函数体中做的第一件事就是检查每个参数的接收值是否有效。你知道吗

例如:

    def turn_on_or_off_power_supplies (engine, power_supply, switch_on_or_off = RemoteRebootConst.OFF):

        '''
            @summary:                                     
                The function turns off or turns on the switch.

            @param engine:
                SSH connection to the switch

            @param switch_on_or_off:
                This sets whether to turn off, or turn on the switch.
                Use the following constants in infra_constants.py:
                    RemoteRebootConst.OFF = off 
                    RemoteRebootConst.ON = on
        '''

        if switch_on_or_off != RemoteRebootConst.ON and switch_on_or_off =! RemoteRebootConst.OFF:
            raise Exception("-ERROR TEST FAILED \n" 
                            "Function Name: turn_on_or_off_power_supplies \n"
                            "Parameter 'switch_on_or_off' \n" 
                            "Expected value: %s or %s \n"
                            "Actual value: %s"
                            % (RemoteRebootConst.ON, RemoteRebootConst.OFF, switch_on_or_off))

Output omitted...

我为什么要这样做?因为这样,如果接收到异常,进行调试的开发人员可以立即知道问题发生在哪个函数中,期望值是多少,实际值是多少。此错误消息使调试此类问题更加容易。你知道吗

如前所述,如果有更多的参数,我将为每个参数编写上述代码。你知道吗

这使我的函数体在代码行数方面变得更大。你知道吗

如果由于接收到无效的参数值(函数名、参数名、期望值、实际值)而出现异常,是否有更为python的方法来打印上述所有详细信息?你知道吗

我可以编写一个函数,它接收4个参数(函数名、参数名、期望值/秒、实际值),然后在每次我想引发这种异常时使用它(这将导致这种类型的每个异常都只是一行代码,而不是几行代码)

我会很感激你的帮助。你知道吗

提前谢谢。你知道吗


Tags: orthe函数代码参数onturnpower
1条回答
网友
1楼 · 发布于 2024-04-19 04:49:59

注意,检查参数的类型是反对duck类型的,duck类型是python哲学的一部分。如果希望其他开发人员能够更轻松地调试代码,则应使用断言:

def turn_on_or_off_power_supplies (engine, power_supply, switch_on_or_off=RemoteRebootConst.OFF):
    assert switch_on_or_off in {RemoteRebootConst.ON, RemoteRebootConst.OFF}, 'wrong argument switch_on_or_off'

有关断言的更多信息,请查看here。 注意,如果使用-O标志优化代码,断言将被删除。你知道吗

相关问题 更多 >