[Tutor] Problem with Learning Python example

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Aug 11 22:25:12 CEST 2005



Hi Terry,


Ok, let's take a look at the problem.  First, let's look at the error
message again:

> Traceback (most recent call last):
>    File "timings.py", line 16, in ?
>      do_timing(100, (makezeros.lots_of_appends, makezeros.one_multiply))
>    File "timings.py", line 9, in do_timing
>      apply(func)
> TypeError: 'tuple' object is not callable


This kind of error will happen if 'func' is weird.  For example:

#######
>>> def sayHi():
...     print "hi"
...
>>> apply(sayHi)
hi
>>> apply(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: 'int' object is not callable
#######

The first call to apply() works because we give apply a function.  The
second call to apply() doesn't work, because 42 isn't something that can
be practically applied as a callable function.


Going back to the bug, let's assume for the moment that in:

    apply(func)

that 'func' really is a tuple, and see how things get that way... ah, I
see it now.



> def do_timing(num_times, *funcs):
[body cut]


Ok, this defines a function called do_timing.  The second argument will
collect any other arguments passed to do_timing and make a tuple out of
them.  So good so far.


This means that if we call dotimings like this:

    do_timings(5, f1, f2, f3, f4)

that num_times=5 and funcs=(f1, f2, f3, f4).

Likewise if we do:

    do_timings(7, f1)

then num_times=7 aand funcs=(f1,).  That is, funcs is a tuple with just
one element in it.


Ok, let's see how the program calls dotiming.

> do_timing(100, (makezeros.lots_of_appends, makezeros.one_multiply))
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Ah!  Ok, that's what's going on.  You mean to do this instead:

    do_timing(100, makezeros.lots_of_appends, makezeros.one_multiply)


What has happened is similar to what happens if we do this:

    do_timings(19, (f1, f2))

which, from our previous examples, allows us to see that this sets
num_times=19, funcs=((f1, f2),).  That is, funcs was a tuple of tuples,
and that's what provokes the problem.


If you have any questions abou this, please feel free to ask.



More information about the Tutor mailing list