- 
          
- 
                Notifications
    You must be signed in to change notification settings 
- Fork 33.3k
          gh-137944: use argparse instead of getopt in timeit
          #137955
        
          New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
        
          
                Misc/NEWS.d/next/Library/2025-08-19-14-52-27.gh-issue-137944.gAFxTV.rst
              
                Outdated
          
            Show resolved
            Hide resolved
        
      | % (number, 's' if number != 1 else '', | ||
| repeat, format_time(best))) | ||
|  | ||
| best = min(timings) | 
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
FTR, best is already computed 5 lines above.
| scales = [(scale, unit) for unit, scale in units.items()] | ||
| scales.sort(reverse=True) | 
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
FTR, this is constant for each invokation, so I can move it outside the function definition.
| Ok, there is one possible breaking change: $ python3.12 -m timeit '1+1' -n1 -r1
Traceback (most recent call last):
...
NameError: name 'n1' is not defined$ ./python -m timeit '1+1' -n1 -r1
1 loop, best of 1: 410 nsec per loopI need to find a way for argparse to gobble everything normally. I don't know if it's possible though. | 
| Answer: use argparse.REMAINDER | 
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ok, so there are a few bits that I could consider separate issues. For instance, if timeit.main() fails at the timer construction, then sys is not restored correctly.
On another note, scales could be extracted outside format_time function but that's mostly some cleanup code which doesn't really warrant a standalone PR.
So I can for now hold this PR because it's not really important. It's indeed a bit fragile and I'm worried about a possible unforseen change of behavior.
At some point, I wanted to reduce the cyclotomic complexity of
main(), but I ended up with more lines than before, which defeated the purpose. While the function is a bit long, it's not that hard to follow, so I would rather keep a smaller diff.argparseintimeit#137944