当参数数量不符时返回TypeError中的函数参数

1 投票
3 回答
2299 浏览
提问于 2025-04-18 00:04

我正在创建自己的Python文件,在里面定义一些函数,这样在绘图的时候就可以直接调用这些函数。这样我只需要加载一个包含各种函数的文件,就能轻松调整我的结果,保持代码的简洁。

我想知道是否可以返回一个函数缺少哪些参数,如果可以的话,应该怎么实现呢?

为了说明我的意思,我定义了以下这个函数:

def func(integer, float):
    return integer / float

如果我现在这样调用这个函数:

print func(2)

它会报错,提示需要两个参数,但我只提供了一个。

TypeError: func() takes exactly 2 arguments (1 given)

因为我计划在未来几年里不断扩展我的函数文件,所以我可能会忘记一些函数和它们需要的参数。因此,我希望能得到一个错误提示,告诉我缺少哪些参数的名字。

举个例子,我希望能得到类似这样的提示:

TypeError: func(integer, float) takes exactly 2 arguments (1 given)

我其实并不太在意需要多少个参数或者提供了多少个参数。对我来说,最重要的是在缺少参数或者多提供一个参数的情况下,能看到像 func(integer, float) 这样的提示。

这可能吗?

提前谢谢你!

3 个回答

0

我终于写出了这段代码,希望能对你有所帮助:

import inspect, traceback

def func(integer, float):
    return integer / float

if __name__ == "__main__":
    try:
        func(2)
    except TypeError:
        print "ERROR: 'func(a, b)' . a is an integer and b is a float"
        print traceback.format_exc()

输出结果:

错误:'func(a, b)'。a 是一个整数,而 b 是一个浮点数。
追踪信息(最近的调用在最前面):
在 "c:/a/script.py" 的第 9 行,调用了
func(2)
类型错误:func() 需要两个参数(只给了一个)

1

我觉得你可能不太会真的想这么做,不过如果非要找个办法的话,可以用getargspec()这个函数,它在inspect模块里,可以用来获取一个Python函数的参数名称和默认值。然后,你可以把所有的函数调用放在try/except块里。

>>> try:
        func(2):
    except TypeError as e:
        print "Error! The function expected {} args".format(getargspec(func).args)
        raise e
Error! The function expected ['integer', 'float'] args 
Traceback (most recent call last):
File "<input>", line 5, in <module>
TypeError: func() takes exactly 2 arguments (1 given)

你也可以把这个过程封装成一个自定义的异常,继承自TypeError(不过这里假设TypeError是因为函数没有接收到正确数量的参数而引发的,这可能有点过于简单化了)。

需要注意的是,你不能在函数对象内部添加代码来实现这个功能,因为Python会在执行函数体内的任何代码之前就抛出TypeError异常。

>>> def another_func(arg1):
        print "Got inside the function - the arg was {}".format(arg1)
>>> another_func("hello")
Got inside the function - the arg was hello
>>> another_func()
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: another_function() takes exactly 1 argument (0 given)
0

经过一番尝试,我找到了最让我满意的答案:

import sys
import numpy

def func(integer = float("nan"), number = float("nan")):
    if numpy.isnan(integer):
        print "Function syntax: func(integer, number)"
        sys.exit()
    return integer * number

func()
>>> Function syntax: func(integer, number)

func(1)
>>> nan

func(3,2)
>>> 6

通过把我的函数变量设置为NaN(不是一个数字),我只能在调用函数时真正给它们赋值才能覆盖它们。不过,由于有一个if语句,我实际上可以在调用函数时不传任何值,仍然打印出这些函数变量。

撰写回答