Calling a list of functions

Ian Kelly ian.g.kelly at gmail.com
Sun Dec 13 12:43:54 EST 2015


On Sun, Dec 13, 2015 at 10:26 AM, Ganesh Pal <ganesh1pal at gmail.com> wrote:
> Hi Team,
>
> Iam on linux and python 2.7  . I have a bunch of functions  which I
> have run sequentially .
> I have put them in a list and Iam calling the functions in the list as
> shown below ,  this works fine for me , please share your
> opinion/views on the same
>
>
> Sample code :
>
> def print1():
>     print "one"
>
> def print2():
>     print "two"
>
> def print3():
>     print "three"
>
> print_test = [print1(),print2(),print3()] //calling the function

If I understand correctly, you want to build the list of functions and
then call them later. If so, this is not quite correct. This is
calling the functions at the time that you build the list and placing
the return values in the list, not the functions.

To build a list of the functions themselves, do:

    print_test = [print1, print2, print3]

> for test in range(len(print_test)):

Iterating over range(len(something)) is usually not correct. Just
iterate over print_test instead. If you really need the indexes, then
iterate over enumerate(print_test).

>   try:
>       print_test[test]
>   except AssertionError as exc:

It looks like some code got cut off here since your exception handler
has no body. Regardless, the exception handler will never be invoked
because print_test[test] is just looking up the results of the
functions that were called when building the list.

To actually call the functions here instead of above, do:

    for test in print_test:
        test()



More information about the Python-list mailing list