The apply Function

The apply(func [,args [,kwargs]]) function can be used to call a function

  • args is a tuple of positional arguments.
  • kwargs is a dictionary of keyword arguments.
     # These two statements are exactly the same
     foo(3,"x", name="Dave", id=12345)
     apply(foo, (3,"x"), {'name':'Dave', 'id':12345 })
     

Why would you use this?

  • Sometimes it is useful to manipulate arguments and call another function
     def fprintf(file,fmt, *args):
         file.write(fmt % args)
     
     def printf(fmt, *args):
         apply(fprintf, (sys.stdout,fmt)+args)
<<< O'Reilly OSCON 2000, Introduction to Python, Slide 84
July 17, 2000, beazley@cs.uchicago.edu
>>>