【问题标题】:Get Keyword Arguments for Function, Python获取函数的关键字参数,Python
【发布时间】:2012-08-08 13:04:31
【问题描述】:
def thefunction(a=1,b=2,c=3):
    pass

print allkeywordsof(thefunction) #allkeywordsof doesnt exist

这将给出 [a,b,c]

有allkeywordsof这样的函数吗?

我不能改变里面的任何东西,thefunction

【问题讨论】:

标签: python function introspection


【解决方案1】:

我想你在找inspect.getargspec:

import inspect

def thefunction(a=1,b=2,c=3):
    pass

argspec = inspect.getargspec(thefunction)
print(argspec.args)

产量

['a', 'b', 'c']

如果您的函数同时包含位置参数和关键字参数,那么查找关键字参数的名称会稍微复杂一些,但并不难:

def thefunction(pos1, pos2, a=1,b=2,c=3, *args, **kwargs):
    pass

argspec = inspect.getargspec(thefunction)

print(argspec)
# ArgSpec(args=['pos1', 'pos2', 'a', 'b', 'c'], varargs='args', keywords='kwargs', defaults=(1, 2, 3))

print(argspec.args)
# ['pos1', 'pos2', 'a', 'b', 'c']

print(argspec.args[-len(argspec.defaults):])
# ['a', 'b', 'c']

【讨论】:

  • 我怎样才能让它只给我agrs
  • inspect.getargspec(thefunction).args
  • argspec.args[-len(argspec.defaults):] 这应该被接受,因为它回答了问题。
  • 没有不尊重 OP 或 Ashwini,但我同意这应该是未来参考的公认答案......
  • getargspecbeen deprecated since v3,请改用getfullargspec
【解决方案2】:

您可以执行以下操作以获得您正在寻找的内容。

>>> 
>>> def funct(a=1,b=2,c=3):
...     pass
... 
>>> import inspect
>>> inspect.getargspec(funct)[0]
['a', 'b', 'c']
>>> 

【讨论】:

    【解决方案3】:

    你想要这样的东西吗:

    >>> def func(x,y,z,a=1,b=2,c=3):
        pass
    
    >>> func.func_code.co_varnames[-len(func.func_defaults):]
    ('a', 'b', 'c')
    

    【讨论】:

    • co_varnames 是一个错误的决定,它还包含非关键字参数,并且主题启动器只需要关键字参数
    • @RostyslavDzinko 是的,你是对的,但问题是 inspect.getargspec() 也返回非关键字参数。
    • @user1513192,这个答案不能解决你描述的问题。如果它符合您的需求 - 重新描述您的问题(我的上面的评论说明了原因)
    • @jamylak 使用它是因为我还没有学习 inspect 并且现在肯定会学习它。 :)
    • 在 python 3 中,func_code 已重命名为 __code__
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    • 2017-10-25
    • 1970-01-01
    • 2013-08-16
    相关资源
    最近更新 更多