Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate dynamic function name and call it using user input in Python

I have 10 to 20 function with prefix name same, & I have to call them as per user input, But am not getting how to call them, I tried using below method but it's not working, Can anyone tell me how should I make function callable.

def pattern_1(no):
    print('First Pattern with ' +str(no)+ ' rows')

def pattern_2(no):
    print('Second Pattern with ' +str(no)+ ' rows')


rows = eval(input('Enter number of rows: '))
pattern_no = eval(input('Enter pattern num [1-10]: '))

cust_fun_name = 'pattern_' + str(pattern_no)

print(cust_fun_name) # Here its print pattern_2 but why function is not get invoked
cust_fun_name()

When I run above code am getting below error

Traceback (most recent call last):                                                                                
  File "/home/main.py", line 22, in <module>                                                                      
    cust_fun_name()                                                                                               
TypeError: 'str' object is not callable
like image 344
Gajanan Kolpuke Avatar asked Sep 17 '18 06:09

Gajanan Kolpuke


People also ask

How do you create a dynamic function in Python?

Python Code can be dynamically imported and classes can be dynamically created at run-time. Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object.

How do you pass a dynamic value to a function in Python?

Passing arguments to the dynamic function is straight forward. We simply can make solve_for() accept *args and **kwargs then pass that to func() . Of course, you will need to handle the arguments in the function that will be called.

How do you create a dynamic variable name in Python?

Use the for Loop to Create a Dynamic Variable Name in Python Along with the for loop, the globals() function will also be used in this method. The globals() method in Python provides the output as a dictionary of the current global symbol table.


1 Answers

if the mapping is static, either make a mapping of function name to function object

mapping = {
  "pattern_1": pattern_1,
  "pattern_2": pattern_2
}

#do not use `eval` on user input!
pattern_no = input('Enter pattern num [1-10]: ')

cust_fun_name = 'pattern_' + str(pattern_no)
cust_func = mapping[cust_fun_name]
# call the function
cust_func()

or get the function object directly from the local namespace

cust_func = locals()['pattern_' + str(pattern_no)]
cust_func()
like image 122
redacted Avatar answered Nov 09 '22 07:11

redacted