is python supports for function array

Thread Starter

ep.hobbyiest

Joined Aug 26, 2014
184
I want to use function array just like we use it in c/c++ in python.
i have used it in c/c++ but I am new to python. I searched but I didn't find anything like that.
I mean if I pass index to the array as a 0 then function saved at 0 should get executed and if I pass 1 then function at 1 will get executed.
 

Irving

Joined Jan 30, 2016
1,496
Something like:

def func1(): return 1
def func2(): return 2
def func3(): return 3

func_array = [func1, func2, func3] # array of functions
index = some_lookup_method() # get the index
func_array[index](a, b, c) # select a function and call it (with parameters if needed)
 

Thread Starter

ep.hobbyiest

Joined Aug 26, 2014
184
Thank you very much.
Can func_array of variable length and can we replace in runtime. I am trying to implement one example now.
 

Irving

Joined Jan 30, 2016
1,496
Func_array is just like any other Python array/list; you can extend, append or insert new elements. Eg
Python:
def func1(x): print('func1',x)
def func2(x): print('func2',x)

funcs = [func1,  func2] #all functions in the list must have same signature

print(funcs)

funcs[1](2)
funcs[0](1)

def func3(x): print('func3',x)

funcs.extend([func3]) #note square brackets as extend takes another list/array of similar objects.

print(funcs)

funcs[2](33)

def func1a(x): print('func1a = ', x)

funcs.insert(1, (func1a)) #note round brackets here and for append function as inserting/appending an object

print(funcs)

funcs[1](42)
Output:
Code:
[<function func1 at 0x2b109ac051f0>, <function func2 at 0x2b109ad6aca0>]
func2 2
func1 1
[<function func1 at 0x2b109ac051f0>, <function func2 at 0x2b109ad6aca0>, <function func3 at 0x2b109ad75040>]
func3 33
[<function func1 at 0x2b109ac051f0>, <function func1a at 0x2b109ad75160>, <function func2 at 0x2b109ad6aca0>, <function func3 at 0x2b109ad75040>]
func1a =  42
 
Last edited:
Top