1

Given a function's name (as a string), can I get that function's parameter list (assuming it exists in the same file)? Basically, here's what I want:

def foo(bar):
    print str(bar);

funcName = 'foo';
printFunctionParameters(funcName);

where I obviously want printFunctionParameters to print bar.

Any suggestions?

3 Answers 3

4

Use the inspect module:

>>> import inspect
>>> def foo(bar):pass
>>> inspect.getargspec(foo)
ArgSpec(args=['bar'], varargs=None, keywords=None, defaults=None)
Sign up to request clarification or add additional context in comments.

5 Comments

That's not quite what I want. Notice that I am given only the function name as a string. Is there any way to use inspect on a string?
I figured it out. In your case, if a = 'foo', then all I have to do is use the eval function along with your suggestion, i.e. inspect.getargspec(eval(a)). Please update your answer so that I can set it as correct. Thanks.
Don't use eval here, just access the module __dict__. Use inspect.getargspec(module.__dict__[funcName]) or inspect.getargspec(globals()[funcName]) depending on whether the function is in the current module or not.
@Evan Thanks for your reply. Your version works too. Is there any specific reason why you prefer it over eval?
1

In Python 3, inspect.getargspec() is deprecated, and you should use inspect.signature()

import inspect
inspect.signature(foo)

Comments

0

Try either,

import inspect

def foo(bar):pass
inspect.getargspec(eval('foo'))

or,

import inspect
import __main__

def foo(bar):pass
inspect.getargspec(__main__.__getattribute__('foo'))

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.