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

时间:2023-01-29 23:21:17
def thefunction(a=1,b=2,c=3):
    pass

print allkeywordsof(thefunction) #allkeywordsof doesnt exist

which would give [a,b,c]

会给[a,b,c]

Is there a function like allkeywordsof?

有没有像allkeywordsof这样的功能?

I cant change anything inside, thefunction

我无法改变内部的任何东西,功能

3 个解决方案

#1


1  

Do you want something like this:

你想要这样的东西:

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

>>> func.func_code.co_varnames[-len(func.func_defaults):]
('a', 'b', 'c')

#2


18  

I think you are looking for inspect.getargspec:

我想你正在寻找inspect.getargspec:

import inspect

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

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

yields

产量

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

If your function contains both positional and keyword arguments, then finding the names of the keyword arguments is a bit more complicated, but not too hard:

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

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']

#3


1  

You can do the following in order to get exactly what you are looking for.

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

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

#1


1  

Do you want something like this:

你想要这样的东西:

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

>>> func.func_code.co_varnames[-len(func.func_defaults):]
('a', 'b', 'c')

#2


18  

I think you are looking for inspect.getargspec:

我想你正在寻找inspect.getargspec:

import inspect

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

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

yields

产量

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

If your function contains both positional and keyword arguments, then finding the names of the keyword arguments is a bit more complicated, but not too hard:

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

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']

#3


1  

You can do the following in order to get exactly what you are looking for.

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

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