alguru
alguru

Reputation: 404

Getting function parameters from function name in python

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?

Upvotes: 1

Views: 161

Answers (3)

paolof89
paolof89

Reputation: 1349

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

import inspect
inspect.signature(foo)

Upvotes: 1

ryanpdwyer
ryanpdwyer

Reputation: 36

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'))

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250901

Use the inspect module:

>>> import inspect
>>> def foo(bar):pass
>>> inspect.getargspec(foo)
ArgSpec(args=['bar'], varargs=None, keywords=None, defaults=None)

Upvotes: 4

Related Questions