Skip to content

timeit setup is affected by test statement #114665

Open
@jaraco

Description

@jaraco

Bug description:

In #114664, I've stumbled on an unexpected behavior in the timeit module.

According to the docs, the "setup" function is run once before repeating the statement under test, but that's not what I'm observing:

 ~ @ py -m timeit --setup 'import sys; assert "csv" not in sys.modules' 'import csv'
Traceback (most recent call last):
  File "/opt/homebrew/Cellar/python@3.12/3.12.1_1/Frameworks/Python.framework/Versions/3.12/lib/python3.12/timeit.py", line 330, in main
    number, _ = t.autorange(callback)
                ^^^^^^^^^^^^^^^^^^^^^
  File "/opt/homebrew/Cellar/python@3.12/3.12.1_1/Frameworks/Python.framework/Versions/3.12/lib/python3.12/timeit.py", line 226, in autorange
    time_taken = self.timeit(number)
                 ^^^^^^^^^^^^^^^^^^^
  File "/opt/homebrew/Cellar/python@3.12/3.12.1_1/Frameworks/Python.framework/Versions/3.12/lib/python3.12/timeit.py", line 180, in timeit
    timing = self.inner(it, self.timer)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<timeit-src>", line 3, in inner
    import sys; assert "csv" not in sys.modules
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError

Compared with

 ~ @ py -m timeit --setup 'import sys; assert "csv" not in sys.modules' pass
100000000 loops, best of 5: 3.89 nsec per loop

In the first, the assertion fails in the setup. But why should it fail? If it's run before the import csv statement, then the assertion should pass. How is it that "csv" is in sys.modules during setup?

CPython versions tested on:

3.12

Operating systems tested on:

macOS

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions