简体   繁体   中英

Get Keyword Arguments for Function, Python

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

print allkeywordsof(thefunction) #allkeywordsof doesnt exist

which would give [a,b,c]

Is there a function like allkeywordsof?

I cant change anything inside, thefunction

I think you are looking for 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']

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM