3

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.

Mihai Zamfir
  • 2,167
  • 4
  • 22
  • 37
  • http://stackoverflow.com/questions/19684434/best-way-to-check-function-arguments-in-python If you have a look around, people have asked this question many times. – Maximas Jun 18 '14 at 08:14
  • This doesn't help me. It is not related to my question and, furthermore, I want to find this stuff outside the function `func`, not inside it. – Mihai Zamfir Jun 18 '14 at 08:16
  • @Maximas That link really doesn't mention default arguments at all... – Mattias Nilsson Jun 18 '14 at 08:18
  • I'm aware, however intuition and a little more research might make it work with default augments :) – Maximas Jun 18 '14 at 08:23
  • Look at the implementation of `inspect.getargs`, if CPython devs could not come up with anything shorter then chances are that no, there is no easier way. – Dima Tisnek Jun 18 '14 at 10:12
  • `inspect`, simplified, would look like this: `foo.func_code.co_varnames[:foo.func_code.co_argcount - len(foo.func_defaults)]`, but that would only work with simple functions, namely excluding Python2 tuple parameters like `def foo(x, (y, z), bar): pass` – Dima Tisnek Jun 18 '14 at 10:17

1 Answers1

1

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']
vaultah
  • 44,105
  • 12
  • 114
  • 143