获取函数,Python的关键字参数

use*_*192 3 python function introspection

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

print allkeywordsof(thefunction) #allkeywordsof doesnt exist
Run Code Online (Sandbox Code Playgroud)

会给[a,b,c]

是否有像allkeywordsof这样的功能?

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

unu*_*tbu 19

我想你正在寻找inspect.getargspec:

import inspect

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

argspec = inspect.getargspec(thefunction)
print(argspec.args)
Run Code Online (Sandbox Code Playgroud)

产量

['a', 'b', 'c']
Run Code Online (Sandbox Code Playgroud)

如果你的函数包含位置和关键字参数,那么找到关键字参数的名称有点复杂,但不是太难:

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']
Run Code Online (Sandbox Code Playgroud)

  • `argspec.args [-len(argspec.defaults):]`这应该被接受,因为它回答了这个问题. (4认同)
  • `inspect.getargspec(thefunction).args` (3认同)

Ash*_*ary 1

你想要这样的东西吗:

>>> def func(x,y,z,a=1,b=2,c=3):
    pass

>>> func.func_code.co_varnames[-len(func.func_defaults):]
('a', 'b', 'c')
Run Code Online (Sandbox Code Playgroud)

  • @user1513192,这个答案不能解决您描述的问题。如果它符合您的需求 - 重新描述您的问题(我上面的评论显示了原因) (4认同)
  • @RostyslavDzinko 是的,你是对的,但问题是 `inspect.getargspec()` 也返回非关键字参数。 (2认同)