Defining a function from a list

Say I have a list of strings: obj = ['One','Two','Three'] , how could I turn each value into this list into a function where they all perform very similar functions? For example:

 def one(): print("one") def two(): print("two") def three(): print("three") 

Now I know that you can predefine functions and use a dictionary (as shown below), but I will say that I wanted many functions to be created, this would require a lot of code, and therefore I would like to know if there is a shorter way , I can do it.

 import tkinter as tk def one(): print("one") def two(): print("two") def three(): print("three") obj = ['One','Two','Three'] func = {'One': one, 'Two': two, 'Three': three} def create_btn(): btns = {} for i in obj: text = i for col in range(1): for row in range(len(obj)): btns[row, col] = tk.Button(canvas, text=str(text), command=func[i]).grid(column=col, row=row) btns[row, col] = canvas.create_window(50, row, window = btns[row, col]) canvas.pack() root = tk.Tk() root.geometry = ("750x600") btn_frame = tk.Frame(root) canvas = tk.Canvas(root) create_btn() root.mainloop() 
+7
function python list
source share
2 answers

Use closure:

 >>> def print_me(string): ... def inner(): ... print(string) ... return inner ... >>> functions = [print_me(s) for s in obj] >>> functions[0]() One >>> functions[1]() Two >>> functions[2]() Three 

Maybe a dict would be more convenient:

 >>> functions = {s:print_me(s) for s in obj} >>> functions['One'] <function print_me.<locals>.wrapper at 0x102078bf8> >>> functions['One']() One >>> 
+8
source share

if you want to manage names, a simple solution with exec:

 L=['one','two','three'] prog='def xxx():print("xxx")' for name in L: exec(prog.replace('xxx',name)) 

Three functions are defined.

 >>>two() two >>> 
+2
source share

All Articles