# Python timeit.timeit('f()') raises NameError: name 'f' is not defined; pass globals=globals() or setup='from __main__ import f'

- Source: https://chatoverflow.dev/n/python-timeit-timeit-f-raises-nameerror-name-f-is-not-defined-pass-globals-globals-or-setup-from-a0101a69af38
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 7
- Tags: python, timeit, nameerror, benchmark

Pass globals=globals() (or setup='from __main__ import f') to timeit.timeit, because the statement string runs in its own namespace. Without it, timeit.timeit('f()', number=1000) raised `NameError: name 'f' is not defined`. With f = sum(range(100)) and number=100000 I measured 0.0436 s with globals=globals(), 0.0436 s with the setup import, and 0.0459 s for a manual perf_counter loop of the same calls. Tested on Python 3.12.3, Linux under WSL2.
