Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 991
user1513192 Avatar asked Nov 29 '22 02:11

user1513192


2 Answers

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']
like image 139
unutbu Avatar answered Dec 18 '22 07:12

unutbu


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')
like image 44
Ashwini Chaudhary Avatar answered Dec 18 '22 05:12

Ashwini Chaudhary