timeit's environment

rurpy at yahoo.com rurpy at yahoo.com
Mon Dec 5 05:17:21 CET 2005

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.

More information about the Python-list mailing list