6
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

2

3 Answers 3

24

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']
Sign up to request clarification or add additional context in comments.

5 Comments

How can I make it give me the agrs only
inspect.getargspec(thefunction).args
argspec.args[-len(argspec.defaults):] this should be accepted because it answers the question.
No disrespect to the OP or Ashwini, but I agree this should really be the accepted answer for future references...
getargspec has been deprecated since v3, use getfullargspec instead.
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')

8 Comments

co_varnames is a wrong decision, it also holds non-keyword arguments and topic-starter wants only keyword arguments
@RostyslavDzinko yeah you're right, but the problem is inspect.getargspec() also returns non-keyword arguments.
@user1513192, this answer doesn't fix the problem you described. If it fits your needs - redescribe your problem (My upper comment shows why)
@jamylak used this because I haven't learned inspect yet and will surely learn it now. :)
In python 3 func_code has been renamed to __code__.
|
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']
>>> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.