Skip to content

Commit 0123a6a

Browse files
committed
fix: address comments
Signed-off-by: yihong0618 <[email protected]>
1 parent ad7dfe1 commit 0123a6a

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

Doc/whatsnew/3.15.rst

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -528,6 +528,14 @@ tarfile
528528
(Contributed by Christoph Walcher in :gh:`57911`.)
529529

530530

531+
timeit
532+
------
533+
534+
* Error tracebacks are now colourised by default. This can be controlled by
535+
:ref:`environment variables <using-on-controlling-color>`.
536+
(Contributed by Yi Hong in :gh:`139374`.)
537+
538+
531539
types
532540
------
533541

Lib/timeit.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -149,17 +149,21 @@ def print_exc(self, file=None, **kwargs):
149149
150150
The optional file argument directs where the traceback is
151151
sent; it defaults to sys.stderr.
152+
153+
The optional colorize keyword argument controls whether the
154+
traceback is colorized; it defaults to False for programmatic
155+
usage. When used from the command line, this is automatically
156+
set based on terminal capabilities.
152157
"""
153-
import _colorize, linecache, traceback, sys
158+
import linecache, traceback, sys
154159
if self.src is not None:
155160
linecache.cache[dummy_src_name] = (len(self.src),
156161
None,
157162
self.src.split("\n"),
158163
dummy_src_name)
159164
# else the source is already stored somewhere else
160165

161-
if 'colorize' not in kwargs:
162-
kwargs['colorize'] = _colorize.can_colorize(file=file)
166+
kwargs['colorize'] = kwargs.get('colorize', False)
163167

164168
traceback.print_exc(file=file, **kwargs)
165169

@@ -263,6 +267,7 @@ def main(args=None, *, _wrap_timer=None):
263267
if args is None:
264268
args = sys.argv[1:]
265269
import getopt
270+
import _colorize
266271
try:
267272
opts, args = getopt.getopt(args, "n:u:s:r:pvh",
268273
["number=", "setup=", "repeat=",
@@ -329,7 +334,8 @@ def callback(number, time_taken):
329334
try:
330335
number, _ = t.autorange(callback)
331336
except:
332-
t.print_exc()
337+
colorize = _colorize.can_colorize()
338+
t.print_exc(colorize=colorize)
333339
return 1
334340

335341
if verbose:
@@ -338,7 +344,8 @@ def callback(number, time_taken):
338344
try:
339345
raw_timings = t.repeat(repeat, number)
340346
except:
341-
t.print_exc()
347+
colorize = _colorize.can_colorize()
348+
t.print_exc(colorize=colorize)
342349
return 1
343350

344351
def format_time(dt):

0 commit comments

Comments
 (0)