[Tutor] Apply() [function calling depends on end parentheses]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Thu Feb 6 14:41:02 2003


On Thu, 6 Feb 2003, Erik Price wrote:

>
> On Thursday, February 6, 2003, at 02:45  AM, Danny Yoo wrote:
>
> > The part that would normally involve 'apply()' is the line:
> >
> >     print cmds[c](*rest)
> >
> >
> > With apply(), that might look like:
> >
> >     print apply(cmds[c], rest)
> >
> >
> >
> > Hope this helps!
>
> Yes, I think I understand ... you can just add parens to the end of any
> name and, if a function has been defined with that name, it will be
> called?


Hi Erik,


Yes, very much so.  The big concept here is that functions are values,
just like numbers and strings:

###
>>> def sayHello():
...     print "hello"
...
>>> sayHello()
hello
>>> def doItTwice(some_function):
...     some_function()
...     some_function()
...
>>> doItTwice(sayHello)
hello
hello
###


We're passing a function value,

###
>>> sayHello
<function sayHello at 0x8159afc>
###

off to our doItTwice() function, as if it were a regular value.  And they
are!  Function values can be stuffed into dictionaries, boxed off into
lists, or even passed off as arguments to other functions.



The thing that makes functions unique from values, like strings and
numbers, is that they can be "called" by using those parentheses at the
end.  In technical terms, functions can be "applied" or "called".  In some
programming languages, the term "apply" is prevalent, but in Python, it
looks like "call" is the term that is most frequently used.  (Perhaps the
'apply()' builtin should have been renamed as 'call()'...  but I'm just
digressing.  *grin*)



That's what makes something like:

###
>>> f = sayHello
>>> f()
hello
###

possible: 'f' is a name that's directed to the same function value.  The
first statement doesn't do an application: it merely does a variable name
assignment, just like any other assignment we've seen.  We can still get
'f' to fire off by doing the parentheses "application".



This is also one reason why, if we forget the parentheses, that "nothing"
happens:

###
>>> sayHello
<function sayHello at 0x8159afc>
>>> f
<function sayHello at 0x8159afc>
###

Nothing fires off, but that's because we haven't told Python to call.  So
the parentheses are the things that triggers functions to "apply" in
Python.


But what happens if we try adding ending parentheses on something that
isn't a function?

###
>>> s = "foobar"
>>> s()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: 'str' object is not callable
###




Please feel free to ask more questions about this.  I hope this helps!