Skip to content

Commit 9a92499

Browse files
committed
py/objexcept: Don't convert errno to str in constructor, do it in print.
OSError's are now printed like: OSError: [Errno 1] EPERM but only if the string corresponding to the errno is found.
1 parent a314b84 commit 9a92499

3 files changed

Lines changed: 14 additions & 10 deletions

File tree

py/moduerrno.c

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -89,12 +89,12 @@ const mp_obj_module_t mp_module_uerrno = {
8989
.globals = (mp_obj_dict_t*)&mp_module_uerrno_globals,
9090
};
9191

92-
mp_obj_t mp_errno_to_str(mp_obj_t errno_val) {
92+
qstr mp_errno_to_str(mp_obj_t errno_val) {
9393
mp_map_elem_t *elem = mp_map_lookup((mp_map_t*)&errorcode_dict.map, errno_val, MP_MAP_LOOKUP);
9494
if (elem == NULL) {
95-
return errno_val;
95+
return MP_QSTR_NULL;
9696
} else {
97-
return elem->value;
97+
return MP_OBJ_QSTR_VALUE(elem->value);
9898
}
9999
}
100100

py/mperrno.h

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -135,9 +135,7 @@
135135
#endif
136136

137137
#if MICROPY_PY_UERRNO
138-
mp_obj_t mp_errno_to_str(mp_obj_t errno_val);
139-
#else
140-
static inline mp_obj_t mp_errno_to_str(mp_obj_t errno_val) { return errno_val; }
138+
qstr mp_errno_to_str(mp_obj_t errno_val);
141139
#endif
142140

143141
#endif // __MICROPY_INCLUDED_PY_MPERRNO_H__

py/objexcept.c

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,16 @@ STATIC void mp_obj_exception_print(const mp_print_t *print, mp_obj_t o_in, mp_pr
108108
mp_print_str(print, "");
109109
return;
110110
} else if (o->args->len == 1) {
111+
#if MICROPY_PY_UERRNO
112+
// try to provide a nice OSError error message
113+
if (o->base.type == &mp_type_OSError && MP_OBJ_IS_SMALL_INT(o->args->items[0])) {
114+
qstr qst = mp_errno_to_str(o->args->items[0]);
115+
if (qst != MP_QSTR_NULL) {
116+
mp_printf(print, "[Errno %d] %q", MP_OBJ_SMALL_INT_VALUE(o->args->items[0]), qst);
117+
return;
118+
}
119+
}
120+
#endif
111121
mp_obj_print_helper(print, o->args->items[0], PRINT_STR);
112122
return;
113123
}
@@ -289,10 +299,6 @@ mp_obj_t mp_obj_new_exception(const mp_obj_type_t *exc_type) {
289299

290300
// "Optimized" version for common(?) case of having 1 exception arg
291301
mp_obj_t mp_obj_new_exception_arg1(const mp_obj_type_t *exc_type, mp_obj_t arg) {
292-
// try to provide a nice string instead of numeric value for errno's
293-
if (exc_type == &mp_type_OSError && MP_OBJ_IS_SMALL_INT(arg)) {
294-
arg = mp_errno_to_str(arg);
295-
}
296302
return mp_obj_new_exception_args(exc_type, 1, &arg);
297303
}
298304

0 commit comments

Comments
 (0)