Getting "global name 'foo' is not defined" with Python's timeit Getting "global name 'foo' is not defined" with Python's timeit python python

Getting "global name 'foo' is not defined" with Python's timeit


Change this line:

t = timeit.Timer("foo()")

To this:

t = timeit.Timer("foo()", "from __main__ import foo")

Check out the link you provided at the very bottom.

To give the timeit module access to functions you define, you can pass a setup parameter which contains an import statement:

I just tested it on my machine and it worked with the changes.


With Python 3, you can use globals=globals()

t = timeit.Timer("foo()", globals=globals())

From the documentation:

Another option is to pass globals() to the globals parameter, which will cause the code to be executed within your current global namespace. This can be more convenient than individually specifying imports


You can try this hack:

import timeitdef foo():    print 'bar'def dotime():    t = timeit.Timer("foo()")    time = t.timeit(1)    print "took %fs\n" % (time,)import __builtin____builtin__.__dict__.update(locals())dotime()