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.

4

3 Answers 3

4

try

print(add_function.__code__.co_varnames)
Sign up to request clarification or add additional context in comments.

1 Comment

add some explanation to your code.
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">}

Comments

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)

2 Comments

add some explanation to your code.
Okay okay, just done :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.