Skip to content

Commit cac939d

Browse files
committed
py/modsys: Add optional sys.tracebacklimit attribute.
With behaviour as per CPython. Signed-off-by: Damien George <damien@micropython.org>
1 parent bc18155 commit cac939d

10 files changed

Lines changed: 117 additions & 3 deletions

File tree

‎docs/library/sys.rst‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,14 @@ Constants
144144

145145
Standard output `stream`.
146146

147+
.. data:: tracebacklimit
148+
149+
A mutable attribute holding an integer value which is the maximum number of traceback
150+
entries to store in an exception. Set to 0 to disable adding tracebacks. Defaults
151+
to 1000.
152+
153+
Note: this is not available on all ports.
154+
147155
.. data:: version
148156

149157
Python language version that this implementation conforms to, as a string.

‎ports/unix/variants/coverage/mpconfigvariant.h‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
#define MICROPY_REPL_EMACS_WORDS_MOVE (1)
3535
#define MICROPY_REPL_EMACS_EXTRA_WORDS_MOVE (1)
3636
#define MICROPY_WARNINGS_CATEGORY (1)
37+
#define MICROPY_MODULE_ATTR_DELEGATION (1)
3738
#define MICROPY_MODULE_GETATTR (1)
3839
#define MICROPY_PY_DELATTR_SETATTR (1)
3940
#define MICROPY_PY_ALL_INPLACE_SPECIAL_METHODS (1)
@@ -44,6 +45,7 @@
4445
#define MICROPY_PY_BUILTINS_HELP (1)
4546
#define MICROPY_PY_BUILTINS_HELP_MODULES (1)
4647
#define MICROPY_PY_SYS_GETSIZEOF (1)
48+
#define MICROPY_PY_SYS_TRACEBACKLIMIT (1)
4749
#define MICROPY_PY_MATH_CONSTANTS (1)
4850
#define MICROPY_PY_MATH_FACTORIAL (1)
4951
#define MICROPY_PY_URANDOM_EXTRA_FUNCS (1)

‎py/modsys.c‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,9 @@ MP_DEFINE_CONST_FUN_OBJ_1(mp_sys_settrace_obj, mp_sys_settrace);
185185

186186
#if MICROPY_PY_SYS_ATTR_DELEGATION
187187
STATIC const uint16_t sys_mutable_keys[] = {
188+
#if MICROPY_PY_SYS_TRACEBACKLIMIT
189+
MP_QSTR_tracebacklimit,
190+
#endif
188191
MP_QSTRnull,
189192
};
190193

‎py/mpconfig.h‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1377,10 +1377,15 @@ typedef double mp_float_t;
13771377
#define MICROPY_PY_SYS_STDIO_BUFFER (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EXTRA_FEATURES)
13781378
#endif
13791379

1380+
// Whether to provide sys.tracebacklimit mutable attribute
1381+
#ifndef MICROPY_PY_SYS_TRACEBACKLIMIT
1382+
#define MICROPY_PY_SYS_TRACEBACKLIMIT (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EVERYTHING)
1383+
#endif
1384+
13801385
// Whether the sys module supports attribute delegation
13811386
// This is enabled automatically when needed by other features
13821387
#ifndef MICROPY_PY_SYS_ATTR_DELEGATION
1383-
#define MICROPY_PY_SYS_ATTR_DELEGATION (0)
1388+
#define MICROPY_PY_SYS_ATTR_DELEGATION (MICROPY_PY_SYS_TRACEBACKLIMIT)
13841389
#endif
13851390

13861391
// Whether to provide "uerrno" module

‎py/mpstate.h‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,9 @@
4141
// variable, but in the future it is hoped that the state can become local.
4242

4343
enum {
44+
#if MICROPY_PY_SYS_TRACEBACKLIMIT
45+
MP_SYS_MUTABLE_TRACEBACKLIMIT,
46+
#endif
4447
MP_SYS_MUTABLE_NUM,
4548
};
4649

‎py/objexcept.c‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -575,6 +575,16 @@ void mp_obj_exception_add_traceback(mp_obj_t self_in, qstr file, size_t line, qs
575575
// append this traceback info to traceback data
576576
// if memory allocation fails (eg because gc is locked), just return
577577

578+
#if MICROPY_PY_SYS_TRACEBACKLIMIT
579+
mp_int_t max_traceback = MP_OBJ_SMALL_INT_VALUE(MP_STATE_VM(sys_mutable[MP_SYS_MUTABLE_TRACEBACKLIMIT]));
580+
if (max_traceback <= 0) {
581+
return;
582+
} else if (self->traceback_data != NULL && self->traceback_len >= max_traceback * TRACEBACK_ENTRY_LEN) {
583+
self->traceback_len -= TRACEBACK_ENTRY_LEN;
584+
memmove(self->traceback_data, self->traceback_data + TRACEBACK_ENTRY_LEN, self->traceback_len * sizeof(self->traceback_data[0]));
585+
}
586+
#endif
587+
578588
if (self->traceback_data == NULL) {
579589
self->traceback_data = m_new_maybe(size_t, TRACEBACK_ENTRY_LEN);
580590
if (self->traceback_data == NULL) {

‎py/runtime.c‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,10 @@ void mp_init(void) {
141141
MP_STATE_THREAD(current_code_state) = NULL;
142142
#endif
143143

144+
#if MICROPY_PY_SYS_TRACEBACKLIMIT
145+
MP_STATE_VM(sys_mutable[MP_SYS_MUTABLE_TRACEBACKLIMIT]) = MP_OBJ_NEW_SMALL_INT(1000);
146+
#endif
147+
144148
#if MICROPY_PY_BLUETOOTH
145149
MP_STATE_VM(bluetooth) = MP_OBJ_NULL;
146150
#endif

‎tests/basics/sys_tracebacklimit.py‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
# test sys.tracebacklimit
2+
3+
try:
4+
try:
5+
import usys as sys
6+
import uio as io
7+
except ImportError:
8+
import sys
9+
import io
10+
except ImportError:
11+
print("SKIP")
12+
raise SystemExit
13+
14+
try:
15+
sys.tracebacklimit = 1000
16+
except AttributeError:
17+
print("SKIP")
18+
raise SystemExit
19+
20+
if hasattr(sys, "print_exception"):
21+
print_exception = sys.print_exception
22+
else:
23+
import traceback
24+
25+
print_exception = lambda e, f: traceback.print_exception(None, e, sys.exc_info()[2], file=f)
26+
27+
28+
def print_exc(e):
29+
buf = io.StringIO()
30+
print_exception(e, buf)
31+
s = buf.getvalue()
32+
for l in s.split("\n"):
33+
# Remove filename.
34+
if l.startswith(" File "):
35+
l = l.split('"')
36+
print(l[0], l[2])
37+
# uPy and CPy tracebacks differ in that CPy prints a source line for
38+
# each traceback entry. In this case, we know that offending line
39+
# has 4-space indent, so filter it out.
40+
elif not l.startswith(" "):
41+
print(l)
42+
43+
44+
def f0():
45+
raise ValueError("value")
46+
47+
48+
def f1():
49+
f0()
50+
51+
52+
def f2():
53+
f1()
54+
55+
56+
def f3():
57+
f2()
58+
59+
60+
def ftop():
61+
try:
62+
f3()
63+
except ValueError as er:
64+
print_exc(er)
65+
66+
67+
ftop()
68+
69+
for limit in range(4, -2, -1):
70+
print("limit", limit)
71+
sys.tracebacklimit = limit
72+
ftop()
73+
74+
75+
# test deleting the attribute
76+
print(hasattr(sys, "tracebacklimit"))
77+
del sys.tracebacklimit
78+
print(hasattr(sys, "tracebacklimit"))

‎tests/run-tests.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -504,6 +504,7 @@ def run_tests(pyb, tests, args, result_dir, num_threads=1):
504504
skip_tests.add("basics/del_local.py") # requires checking for unbound local
505505
skip_tests.add("basics/exception_chain.py") # raise from is not supported
506506
skip_tests.add("basics/scope_implicit.py") # requires checking for unbound local
507+
skip_tests.add("basics/sys_tracebacklimit.py") # requires traceback info
507508
skip_tests.add("basics/try_finally_return2.py") # requires raise_varargs
508509
skip_tests.add("basics/unboundlocal.py") # requires checking for unbound local
509510
skip_tests.add("extmod/uasyncio_event.py") # unknown issue

‎tests/unix/extra_coverage.py.exp‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,8 @@ utime utimeq
4545
argv atexit byteorder exc_info
4646
exit getsizeof implementation maxsize
4747
modules path platform print_exception
48-
stderr stdin stdout version
49-
version_info
48+
stderr stdin stdout tracebacklimit
49+
version version_info
5050
ementation
5151
# attrtuple
5252
(start=1, stop=2, step=3)

0 commit comments

Comments
 (0)