简体   繁体   English

当函数调用缺少Python中的参数时如何引发异常

[英]How to raise exception when function call is missing an argument in Python

If I have the function 如果我有功能

def my_function(a,b,c):

and when the user calls the function, they omit the last argument 当用户调用函数时,他们省略了最后一个参数

print(my_function(a,b))

what exception should I raise? 我应该提出什么例外?

After discussion in the comment, it seems that what you want to do is catch an exception to pass a default argument if one was missing. 在评论中进行讨论之后,似乎您想做的就是捕获一个异常,以便在缺少默认参数时传递默认参数。

First of all, Python will already raise a TypeError if an argument is missing. 首先,如果缺少参数,Python将已经引发TypeError

But you do not need to catch it to have default arguments since Python already provides a way to do this. 但是您无需捕获它即可使用默认参数,因为Python已经提供了一种执行此操作的方法。

def my_function(a, b, c=0):
    pass

my_function(1, 2, 3) # This works fine
my_function(1, 2) # This works as well an used 0 as default argument for c

As others have mentioned, Python will raise a TypeError if a function is called with an incorrect number of statically declared arguments. 正如其他人提到的那样,如果使用错误数量的静态声明参数调用函数,Python将引发TypeError It seems there is no practical reason to override this behavior to raise your own custom error message since Python's: 似乎没有实际的理由可以覆盖此行为以引发您自己的自定义错误消息,因为Python的原因是:

TypeError: f() takes 2 positional arguments but 3 were given

is quite telling. 很有说服力。

However, if you want to do this, and perhaps optionally allow a second argument, you can use *args . 但是,如果要执行此操作,并且可能选择允许第二个参数,则可以使用*args

def my_function(a, *args):
    b = None
    if len(args) > 1:
        raise TypeError("More than 2 arguments not allowed.")
    elif args:
        b = args[0]

    # do something with a and possibly b.

Edit: The other answer suggesting a default keyword argument is more appropriate given new additional details in OP's comment. 编辑:给出OP注释中的新附加详细信息,建议使用默认关键字参数的另一个答案更合适。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM