I've come across some strange behaviour trying to time python scripts. Minimum example:
foobar.py:
foo = 'Hello'
print(''.join(c for c in foo if c not in 'World'))
print(''.join(c for c in 'World' if c not in foo))
timer.py:
import timeit
timeit.repeat(stmt="exec(open('foobar.py').read())", repeat=1, number=1)
When I run foobar.py, I get the expected output:
> python3 foobar.py
He
Wrd
However, when I run timer.py, I get the following error:
> python3 timer.py
He
Traceback (most recent call last):
File "timer.py", line 2, in <module>
timeit.repeat(stmt="exec(open('foobar.py').read())", repeat=1, number=1)
File "/usr/lib/python3.7/timeit.py", line 237, in repeat
return Timer(stmt, setup, timer, globals).repeat(repeat, number)
File "/usr/lib/python3.7/timeit.py", line 204, in repeat
t = self.timeit(number)
File "/usr/lib/python3.7/timeit.py", line 176, in timeit
timing = self.inner(it, self.timer)
File "<timeit-src>", line 6, in inner
File "<string>", line 3, in <module>
File "<string>", line 3, in <genexpr>
NameError: name 'foo' is not defined
Perhaps the most bizzare thing about it is that the first print statement in foobar.py works fine, while the second one does not. Executing foobar.py using exec without timeit wrapper works fine as well.
Anyone have an explanation for this odd behaviour?