priestc
priestc

Reputation: 35170

How to get keyword arguments for a function

>>> def test(arg1, arg2, arg3=None): pass
>>> test.func_code.co_varnames
('arg1', 'arg2, 'arg3')

What I want is something like:

{'args': ('arg1', 'arg2'), 'kwargs': {'arg3': None}}

Is there a way to achieve this?

Upvotes: 1

Views: 1072

Answers (1)

ThiefMaster
ThiefMaster

Reputation: 318488

You can use inspect.getargspec() to get the arguments a function expects.

>>> inspect.getargspec(test)
ArgSpec(args=['arg1', 'arg2', 'arg3'], varargs=None, keywords=None,
        defaults=(None,))

As you can see the keywords attribute is None as any argument can be passed as a kwarg; it would contain the name of the **kwargs argument if one existed.

To get a dict mapping the argument names to default values you can use this code with as being the ArgSpec returned by inspect.getargspec():

defaults = dict(zip(*[reversed(l) for l in (as.args, as.defaults or [])]))

Upvotes: 5

Related Questions