user1513192
user1513192

Reputation: 1153

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

Upvotes: 6

Views: 6288

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250901

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

Upvotes: 1

unutbu
unutbu

Reputation: 879331

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

Upvotes: 24

Alagappan Ramu
Alagappan Ramu

Reputation: 2358

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

Upvotes: 1

Related Questions