< BACKMake Note | BookmarkCONTINUE >
156135250194107072078175030179198180024228156016206217188240240204174053205054004235083191

*apply()

The first built-in function we are looking at is apply(). The apply() function is the most basic of the four and is simply used to pass in a function object along with any parameters. apply() will then invoke that function with the given arguments. There is no special magic here; apply() works exactly the way you think it does, so the following pair of calls are practically identical:

					
foo(3, 'pyramid')     ?      apply(foo, (3, 'pyramid'))

				

Alternatively, the arguments can be stored in a tuple, and then the function can be called with apply():

					
args = (4, 'eve', 79)
apply(foo, args)

				

Note this is not the same as foo(args) which is calling foo() with a single argument (a tuple). Rather, using apply() means calling foo() with three arguments, the elements of the tuple.

If you wanted to call the built-in function dir() from the interpreter, you could either execute it directly, or use apply(). In this example, they both have the same effect since no arguments are involved.

					
dir()        ?     apply(dir)

				

Below, we perform both function calls in the interpreter to show you they produce identical results:

					
>>> dir()
['__builtins__', '__doc__', '__name__']
>>>
>>> apply(dir)
['__builtins__', '__doc__', '__name__']

				

You may be wondering… why would I ever need to use apply() when I can just make a function call? Is there ever a need to do the following? Not only does it require more typing on my part, but the syntax is more complicated.

apply() can be used as an effective tool in certain situations. One scenario where apply() comes in handy is when you need to call a function, but its arguments are generated dynamically. Such situations usually involve assembling an argument list. In our math game in Example 11.3 (matheasy.py), we generate a two-item argument list to send to the appropriate arithmetic function.

The matheasy.py application is basically an arithmetic math quiz game for children where an arithmetic operation is randomly chosen between addition, subtraction, and multiplication. We use the functional equivalents of these operators, add(), sub(), and mul(), all found in the operator module. We then generate the list of arguments (two, since these are binary operators/operations). Then random numbers are chosen as the operands. Since we do not want to support negative numbers in this more elementary edition of this application, we sort our list of two numbers in largest-to-smallest order, then call apply() with this argument list and the randomly-chosen arithmetic operator to obtain the correct solution to the posed problem. apply() makes a good choice for our application for two reasons:

Example 11.3. Arithmetic Game Using apply()(matheasy.py)

Randomly chooses numbers and an arithmetic function, displays the question, and verifies the results. Shows answer after three wrong tries and does not continue until the user enters the correct answer.

 <$nopage>
001 1  #!/usr/bin/env python
002 2  from string import lower
003 3  from operator import add, sub, mul
004 4  from random import randint, choice
005 5
006 6  ops = { '+': add, '-': sub, '*': mul }
007 7  MAXTRIES = 2
008 8
009 9  def doprob():
010 10     op = choice('+-*')
011 11     nums = [randint(1,10), randint(1,10)]
012 12     nums.sort() ; nums.reverse()
013 13     ans = apply(ops[op], nums)
014 14     pr = '%d %s %d = ' % (nums[0], op, nums[1])
015 15     oops = 0
016 16     while 1:
017 17         try: <$nopage>
018 18             if int(raw_input(pr)) == ans:
019 19                 print 'correct'
020 20                 break <$nopage>
021 21             if oops == MAXTRIES:
022 22                 print 'answer\n%s%d'%(pr,ans)
023 23             else: <$nopage>
024 24                 print 'incorrect… try again'
025 25                 oops = oops + 1
026 26         except (KeyboardInterrupt, \
027 27                 EOFError, ValueError):
028 28             print 'invalid input… try again'
029 29
030 30 def main():
031 31     while 1:
032 32         doprob()
033 33         try: <$nopage>
034 34             opt = lower(raw_input('Again? '))
035 35         except (KeyboardInterrupt, EOFError):
036 36             print ; break <$nopage>
037 37         if opt and opt[0] == 'n':
038 38             break <$nopage>
039 39
040 40 if __name__ == '__main__':
041 41     main()
042  <$nopage>
  • Argument list hand-built

  • Function randomly chosen

Since we do not know what our arguments are nor do we know what function we will be calling for each math question posed to the user, apply() makes for a flexible solution.


Last updated on 9/14/2001
Core Python Programming, © 2002 Prentice Hall PTR

< BACKMake Note | BookmarkCONTINUE >

© 2002, O'Reilly & Associates, Inc.