Skip to content

Commit ef63ab5

Browse files
committed
py/objstr: Make sure that b"%s" % b"foo" uses undecorated bytes value.
I.e. the expected result for above is b"foo", whereas previously we got b"b'foo'".
1 parent 0a4eb4d commit ef63ab5

2 files changed

Lines changed: 10 additions & 2 deletions

File tree

py/obj.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -390,6 +390,7 @@ typedef enum {
390390
PRINT_REPR = 1,
391391
PRINT_EXC = 2, // Special format for printing exception in unhandled exception message
392392
PRINT_JSON = 3,
393+
PRINT_RAW = 4, // Special format for printing bytes as an undercorated string
393394
PRINT_EXC_SUBCLASS = 0x80, // Internal flag for printing exception subclasses
394395
} mp_print_kind_t;
395396

py/objstr.c

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ STATIC void str_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t
121121
#else
122122
bool is_bytes = true;
123123
#endif
124-
if (!MICROPY_PY_BUILTINS_STR_UNICODE && kind == PRINT_STR && !is_bytes) {
124+
if (kind == PRINT_RAW || (!MICROPY_PY_BUILTINS_STR_UNICODE && kind == PRINT_STR && !is_bytes)) {
125125
mp_printf(print, "%.*s", str_len, str_data);
126126
} else {
127127
if (is_bytes) {
@@ -1296,6 +1296,7 @@ STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, mp_uint_t n_args, const mp_o
12961296

12971297
GET_STR_DATA_LEN(pattern, str, len);
12981298
const byte *start_str = str;
1299+
bool is_bytes = MP_OBJ_IS_TYPE(pattern, &mp_type_bytes);
12991300
int arg_i = 0;
13001301
vstr_t vstr;
13011302
mp_print_t print;
@@ -1444,7 +1445,13 @@ STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, mp_uint_t n_args, const mp_o
14441445
vstr_t arg_vstr;
14451446
mp_print_t arg_print;
14461447
vstr_init_print(&arg_vstr, 16, &arg_print);
1447-
mp_obj_print_helper(&arg_print, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
1448+
mp_print_kind_t print_kind = (*str == 'r' ? PRINT_REPR : PRINT_STR);
1449+
if (print_kind == PRINT_STR && is_bytes && MP_OBJ_IS_TYPE(arg, &mp_type_bytes)) {
1450+
// If we have something like b"%s" % b"1", bytes arg should be
1451+
// printed undecorated.
1452+
print_kind = PRINT_RAW;
1453+
}
1454+
mp_obj_print_helper(&arg_print, arg, print_kind);
14481455
uint vlen = arg_vstr.len;
14491456
if (prec < 0) {
14501457
prec = vlen;

0 commit comments

Comments
 (0)