Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get function arguments which are not default

Tags:

python

I have this function:

def func(a, b, c=1, d=2):
    pass

With this:

import inspect
inspect.getargspec(func)

I get this result:

ArgSpec(args=['a', 'b', 'c', 'd'], varargs=None, keywords=None, defaults=(1, 2))

Is there an easier way to find the arguments of a function which do not take default values? With the statement above I have to do something ugly like this

ab = args[:-len(defaults)]

to retrieve those arguments. ab will now be ['a', 'b']

Thanks.

[EDIT] For more clarifications: I want to do this inspect outside the function func, not inside it.

like image 289
Mihai Zamfir Avatar asked Jul 04 '26 12:07

Mihai Zamfir


1 Answers

For Python 3.3 and newer using Signature:

In [15]: [x for x, y in inspect.signature(func).parameters.items() if y.default is y.empty]
Out[15]: ['a', 'b']
like image 166
vaultah Avatar answered Jul 07 '26 02:07

vaultah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!