timeit's environment

rurpy at yahoo.com rurpy at yahoo.com
Mon Dec 5 00:21:01 EST 2005

Alex Martelli wrote:
> <rurpy at yahoo.com> wrote:
> > Why doesn't the following work?  It generates a "NameError: global
> > name 'data' is not defined" error.
> >
> >   import timeit
> >
> >   global data
> >   data = [3,8,4,8,6,0,5,7,2,1]
> >
> >   env = "global data; x = data"
> >
> >   print timeit.Timer('x.sort()', env).timeit()
> >   print timeit.Timer('x.sort(cmp=cmp', env).timeit()
> >
> > How can I get timeit() to see an external (to it) variable?
> > (In the real program 'data' is very expensive to create and
> > contains non-reproducable data and the two timeit calls
> > must be run on identical objects.
> You have to use 'from __main__ import data as x' rather than just say
> 'global data; x=data', because timeit is a separate module from your
> __main__ one.

Ahh, (slaps forehead) that makes sense.  Thank you.

After posting I looked again at the documentation and at the
bottom of the example subsection, they also mention using
import (although without explaining why.)

Since I've been bitching about documentation in another
thread, I'm curious...  Would it be obvious to anyone of
low to intermediate python skills that using global would
not work in this case?  Would it be obvious that using an
import is the answer?  Or can I blame this partially on the
documentation? :-)  I think the scoping issue could have
at least been mentioned in the Timer class or timeit method
descriptions.  There is no mention there of exactly what
environment the code is run in.

More information about the Python-list mailing list