Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find names of positional arguments through introspection

Tags:

python

Is there a way to figure out the names of the positional arguments to a python function?

def foo(arg1, arg2):
  pass

f=foo
# How do I find out want the 1st argument to f is called? I want 'arg1' as an answer
like image 658
bradtgmurray Avatar asked Jun 06 '11 16:06

bradtgmurray


People also ask

What are positional arguments with example?

An example of positional arguments can be seen in Python's complex() function. This function returns a complex number with a real term and an imaginary term. The order that numbers are passed to the complex() function determines which number is the real term and which number is the imaginary term.

What are the positional arguments?

A positional argument means its position matters in a function call. A keyword argument is a function argument with a name label. Passing arguments as keyword arguments means order does not matter.

What is the meaning of a positional argument determined by?

its value. the argument's name specified along with its value.

What does takes 1 positional argument but 2 were given?

The Python "TypeError: takes 1 positional argument but 2 were given" occurs for multiple reasons: Forgetting to specify the self argument in a class method. Forgetting to specify a second argument in a function's definition. Passing two arguments to a function that only takes one.


1 Answers

The function inspect.getargspec() does what you need in Python 2.

In Python 3, this has been deprecated, and you should instead use signature.

like image 78
Sven Marnach Avatar answered Sep 29 '22 12:09

Sven Marnach