gpt4 book ai didi

python - 如何获取 Python 中内置函数的参数个数?

转载 作者:太空宇宙 更新时间:2023-11-03 15:28:26 24 4
gpt4 key购买 nike

我需要以编程方式获取函数所需的参数数量。对于在模块中声明的函数,这是微不足道的:

myfunc.func_code.co_argcount

但是内置函数没有func_code 属性。还有另一种方法吗?否则我无法使用内置插件,必须在我的代码中重新编写它们。

[补充]感谢您的回复,希望它们有用。我改用了 Pypy。

最佳答案

看看下面从 here 复制的函数.这可能是你能做的最好的。请注意有关 inspect.getargspec 的注释。

def describe_builtin(obj):
""" Describe a builtin function """

wi('+Built-in Function: %s' % obj.__name__)
# Built-in functions cannot be inspected by
# inspect.getargspec. We have to try and parse
# the __doc__ attribute of the function.
docstr = obj.__doc__
args = ''

if docstr:
items = docstr.split('\n')
if items:
func_descr = items[0]
s = func_descr.replace(obj.__name__,'')
idx1 = s.find('(')
idx2 = s.find(')',idx1)
if idx1 != -1 and idx2 != -1 and (idx2>idx1+1):
args = s[idx1+1:idx2]
wi('\t-Method Arguments:', args)

if args=='':
wi('\t-Method Arguments: None')

print

关于python - 如何获取 Python 中内置函数的参数个数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3276635/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com