[Tutor] Passing functions(with parameters) as paramiters to (looping)functions.

Prasad, Ramit ramit.prasad at jpmorgan.com
Tue Aug 16 19:26:56 CEST 2011

>def loop(fn ):
>     for i in range(5):
>         fn(  )
>def this_function(a=" i am not a string"):
>     print( a )
>loop(this_function("I am a string") )  ## note the only change is here
>## With this as output:
> >>>
>I am a string
>Traceback (most recent call last):
>   File "/home/jeff/MyPythonStuff/call_sub.py", line 9, in <module>
>     loop(this_function("I am a string") )
>   File "/home/jeff/MyPythonStuff/call_sub.py", line 4, in loop
>     fn(  )
>TypeError: 'NoneType' object is not callable
> >>>

NOTE: All code is untested.

You get a NoneType because this_function returns a None. What is happening is the this_function("xxx") gets called first and then that return value gets passed into loop as 'loop(None)'. I am not sure exactly what you are trying to do, but I would probably do something like passing in a list of arguments.

loop(this_function, iterable_of_arguments)

def loop(fn, args):
     for arg in args :
         fn( arg )

The way I would get an argument gets passed to this_function is really dependent on your goal. You may want to look at itertools / map libraries as well for more options.


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  

More information about the Tutor mailing list