python函数获取 *arg名称

发布于 2025-02-08 10:51:14 字数 227 浏览 0 评论 0原文

给定一个python函数,

def func(a, b, *c, **d):
    pass

我可以得到参数的名称:

>>> print(func.__code__.co_varnames)
('a', 'b', 'c', 'd')

但是我怎么知道,c是 *args,d是** kwargs?

Given a python function

def func(a, b, *c, **d):
    pass

I can get the names of arguments:

>>> print(func.__code__.co_varnames)
('a', 'b', 'c', 'd')

But how do I know, that c is *args and d is **kwargs??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

好久不见√ 2025-02-15 10:51:14

据我所知,仅通过签名对象访问Inspect.Signature.signature才能访问此信息。其中 函数获取信息,我不知道。 (这可能是实施中存储的东西,以其他方式在Python级别上没有暴露。)

>>> import inspect
>>> inspect.signature(func).parameters['a'].kind
<_ParameterKind.POSITIONAL_OR_KEYWORD: 1>
>>> inspect.signature(func).parameters['c'].kind
<_ParameterKind.VAR_POSITIONAL: 2>
>>> inspect.signature(func).parameters['d'].kind
<_ParameterKind.VAR_KEYWORD: 4>

如果您查看 _signature_from_function ,您会看到它通过查看func .__ Code __. co_objects 并对您在func .__代码__. co_varnames中看到的名称上的左右逻辑应用一些逻辑。

As far as I know, this information is only accessible via the Signature object returned by inspect.signature. Where that function gets the information, I do not know. (It may be something stored by the implementation that is not otherwise exposed at the Python level.)

>>> import inspect
>>> inspect.signature(func).parameters['a'].kind
<_ParameterKind.POSITIONAL_OR_KEYWORD: 1>
>>> inspect.signature(func).parameters['c'].kind
<_ParameterKind.VAR_POSITIONAL: 2>
>>> inspect.signature(func).parameters['d'].kind
<_ParameterKind.VAR_KEYWORD: 4>

If you look at the definition of _signature_from_function, you'll see it determines the kind by looking at the flags in func.__code__.co_objects and applying some left-to-right logic on the names you see in func.__code__.co_varnames.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文