[Tutor] Tutor Digest, Vol 15, Issue 40

Kent Johnson kent37 at tds.net
Tue May 17 14:06:59 CEST 2005


J. Gabriel Schenz wrote:
> Now, I am new to Python as well, but it seems like apply might not be
> completely superfluous.  I was thinking that if one were using a functional
> programming style, and had to apply a function determined at runtime to an
> argument, then one could use this apply to do so.  Granted, you could also
> have a dictionary of functions and call the function required as determined
> at runtime, but this is stylistically different.
> 
> If I am off base on this, I would appreciate someone explaining why.  That
> way I can learn this elegant language better.

apply() is superfluous. apply(function, args[, keywords]) is exactly equivalent to function(*args, 
[**keywords]). So however you are determining the function to use with apply, you can call it 
directly with the newer syntax. In each case, the variable 'function' will be bound to a function 
object. For example,

  >>> def foo():
  ...   print 'foo'
  ...
  >>> def bar():
  ...   print 'bar'
  ...
  >>> def pick(arg):
  ...   if arg:
  ...     return foo
  ...   else:
  ...     return bar
  ...
  >>> myFunc = pick(True)
  >>> apply(myFunc, ())
foo
  >>> myFunc()
foo
  >>> myFunc = pick(False)
  >>> myFunc()
bar

Kent



More information about the Tutor mailing list