Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list function argument names [duplicate]

Is there a way to get the parameter names a function takes?

def foo(bar, buz):     pass  magical_way(foo) == ["bar", "buz"] 
like image 840
Bemmu Avatar asked Aug 19 '10 00:08

Bemmu


People also ask

What is * in Python parameter list?

It means that parameter(s) that comes after * are keyword only parameters.

How do I get a list of function arguments in Python?

To extract the number and names of the arguments from a function or function[something] to return ("arg1", "arg2"), we use the inspect module. The given code is written as follows using inspect module to find the parameters inside the functions aMethod and foo.

What does * mean in * args in Python?

Python has *args which allow us to pass the variable number of non keyword arguments to function. In the function, we should use an asterisk * before the parameter name to pass variable length arguments.

Can a list be an argument in function Python?

You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.


2 Answers

Use the inspect module from Python's standard library (the cleanest, most solid way to perform introspection).

Specifically, inspect.getargspec(f) returns the names and default values of f's arguments -- if you only want the names and don't care about special forms *a, **k,

import inspect  def magical_way(f):     return inspect.getargspec(f)[0] 

completely meets your expressed requirements.

like image 109
Alex Martelli Avatar answered Oct 13 '22 19:10

Alex Martelli


>>> import inspect >>> def foo(bar, buz): ...     pass ...  >>> inspect.getargspec(foo) ArgSpec(args=['bar', 'buz'], varargs=None, keywords=None, defaults=None) >>> def magical_way(func): ...     return inspect.getargspec(func).args ...  >>> magical_way(foo) ['bar', 'buz'] 
like image 25
John La Rooy Avatar answered Oct 13 '22 19:10

John La Rooy