Skip to content

Commit 7317e34

Browse files
committed
py/objstr: Give correct behaviour when passing a dict to %-formatting.
This patch fixes two main things: - dicts can be printed directly using '%s' % dict - %-formatting should not crash when passed a non-dict to, eg, '%(foo)s'
1 parent 87882e1 commit 7317e34

File tree

1 file changed

+6
-7
lines changed

1 file changed

+6
-7
lines changed

py/objstr.c

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -282,19 +282,14 @@ const byte *find_subbytes(const byte *haystack, mp_uint_t hlen, const byte *need
282282
mp_obj_t mp_obj_str_binary_op(mp_uint_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
283283
// check for modulo
284284
if (op == MP_BINARY_OP_MODULO) {
285-
mp_obj_t *args;
286-
mp_uint_t n_args;
285+
mp_obj_t *args = &rhs_in;
286+
mp_uint_t n_args = 1;
287287
mp_obj_t dict = MP_OBJ_NULL;
288288
if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
289289
// TODO: Support tuple subclasses?
290290
mp_obj_tuple_get(rhs_in, &n_args, &args);
291291
} else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_dict)) {
292-
args = NULL;
293-
n_args = 0;
294292
dict = rhs_in;
295-
} else {
296-
args = &rhs_in;
297-
n_args = 1;
298293
}
299294
return str_modulo_format(lhs_in, n_args, args, dict);
300295
}
@@ -1376,6 +1371,10 @@ STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, mp_uint_t n_args, const mp_o
13761371

13771372
// Dictionary value lookup
13781373
if (*str == '(') {
1374+
if (dict == MP_OBJ_NULL) {
1375+
mp_raise_TypeError("format requires a dict");
1376+
}
1377+
arg_i = 1; // we used up the single dict argument
13791378
const byte *key = ++str;
13801379
while (*str != ')') {
13811380
if (str >= top) {

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy