gpt4 book ai didi

python - 是否有不能用关键字参数调用的内置函数的完整列表?

转载 作者:太空狗 更新时间:2023-10-29 21:06:54 29 4
gpt4 key购买 nike

答案中提到的人 a1 , a2那个

Due to the way the Python C-level APIs developed, a lot of built-in functions and methods don't actually have names for their arguments.

我发现它真的很烦人,因为我无法通过查看文档来了解它。例如,eval

eval(expression, globals=None, locals=None)

然后我写了这行代码

print(eval('a+b', globals={'a':1, 'b':2}))

并得到 TypeError: eval() takes no keyword arguments。那么是否有此类功能的完整列表?我如何知道一个函数是否允许有关键字参数?

最佳答案

在 Python 3.5 中,您可以检查内置函数的 __text_signature__:

>>> eval.__text_signature__
'($module, source, globals=None, locals=None, /)'

>>> abs.__text_signature__
'($module, x, /)'
>>> abs(x=5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: abs() takes no keyword arguments

(x 不能用作关键字参数)

/ 表示后面的参数可以用作关键字参数。比照

>>> compile.__text_signature__
'($module, /, source, filename, mode, flags=0,\n dont_inherit=False, optimize=-1)'
>>> compile(source='foo', filename='bar', mode='exec')
<code object <module> at 0x7f41c58f0030, file "bar", line 1>

当然3.5也有bug:

>>> sorted.__text_signature__
'($module, iterable, key=None, reverse=False)'

尽管根据issue 26729 in the Python bug tracker ,在 iterable 之后应该有 / 因为 iterable 不能用作关键字参数。


遗憾的是,此信息在 Python 文档本身中尚不可用。

关于python - 是否有不能用关键字参数调用的内置函数的完整列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36617555/

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