gpt4 book ai didi

python - 告诉函数如何接收参数?

转载 作者:太空狗 更新时间:2023-10-30 00:17:26 25 4
gpt4 key购买 nike

我想知道在 cpython 中是否可以进行以下自省(introspection):

>>> def potato(x=69):
... if x == 69 and ???:
... print '69 was taken from argument defaults'
... if x == 69 and ???:
... print '69 was passed as positional arg'
... if x == 69 and ???:
... print '69 was passed as kwarg'
...
>>> potato()
69 was taken from argument defaults
>>> potato(69)
69 was passed as positional arg
>>> potato(x=69)
69 was passed as kwarg

我对 python2 和 python3 的答案都感兴趣,如果它们不同的话。

任何涉及inspecttracebackpdbsys._getframe 等的黑魔法在这里都是允许的。当然,修改函数的 argspec 是不允许的。

最佳答案

虽然框架有一个名为 code_context 的字符串,但它看起来不像 inspect 可以直接提供此信息,它为您提供了调用该函数的源代码行。问题是人们必须重写一个小的解析器才能理解它。

这是一个更简单的解决方案,它基于您要检查的函数的包装器。它不会改变 arg 规范,arg 验证也不会改变:

import inspect

def track_args(func):
def tracker(*args, **kwargs):
r = func(*args, **kwargs)
for arg_num,arg_name in enumerate(inspect.getargspec(func)[0]):
if arg_name in kwargs:
print "%s was provided as keyword arg" % arg_name
elif arg_num < len(args):
print "%s was provided as positional arg" % arg_name
else:
print "%s was provided by default value" % arg_name
return r
return tracker

@track_args
def f(a, b, c=30):
print "I'm f()"

f(20, b=10)
f(20)

具有有效参数的结果:

I'm f()
a was provided as positional arg
b was provided as keyword arg
c was provided by default value

参数无效的结果:

Traceback (most recent call last):
File "test.py", line 21, in <module>
f(20)
File "test.py", line 5, in tracker
r = func(*args, **kwargs)
TypeError: f() takes at least 2 arguments (1 given)

关于python - 告诉函数如何接收参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23368194/

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