1

Problem

Assume that a function is defined:

def add_func(a, b):
  return a + b

I would like to dynamically find out how many variables add_func can take in. For example, by using some attributes of the function such as

> add_func.__num_variables__

I have looked up all the attributes of the defined function, but none of the attributes give me the information that I need.

> dir(add_func)
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

Would appreciate

Why

A little explanation on why I have to dynamically find out how many variables are in a function. The function is provided by a customer, and the function name is always the same, but the number of variables can updated by customer. On my side, I need to create a web page (form), which should have as many inputs as the number of the variables in the function. Theoretically I can force the customer to maintain a config file, but before that I'd like to explore if Python as a scripting language is able to support my use case.

Justin Li
  • 635
  • 1
  • 7
  • 18
  • 1
    Why not have a dynamic number of arguments for your function? – Austin Aug 05 '20 at 06:16
  • 2
    use a dict instead of loose variables? – RichieV Aug 05 '20 at 06:19
  • 2
    Does this answer your question? [How can I find the number of arguments of a Python function?](https://stackoverflow.com/questions/847936/how-can-i-find-the-number-of-arguments-of-a-python-function) – FishingCode Aug 05 '20 at 06:28
  • Does this answer your question? [How to get method parameter names?](https://stackoverflow.com/questions/218616/how-to-get-method-parameter-names) – Fran Aug 05 '20 at 06:36

3 Answers3

4

try

print(add_function.__code__.co_varnames)
vpdiongzon
  • 350
  • 1
  • 5
1

The following code will get you a dictionary for the parameters present.

from inspect import signature
sig=signature(add_func)
print(dict(sig.parameters))

Expected Output

{'a': <Parameter "a">, 'b': <Parameter "b">}

Anant Kumar
  • 601
  • 1
  • 17
1

Try this:

import signature module from inspect library:

from inspect import signature

create a functions (in this case it takes 2 arguments)

def test(a, b):
    pass

assign the function to the module signature and store in a variable (here sig)

sig = signature(test)

print to check the arguments passed inside the function output should be

print(sig)
(a, b)
Marco
  • 57
  • 9