Skip to content

Commit 000730e

Browse files
committed
py/objstr: Simplify error handling for bad conversion specifier.
1 parent c9fa667 commit 000730e

2 files changed

Lines changed: 20 additions & 10 deletions

File tree

py/objstr.c

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -894,9 +894,17 @@ mp_obj_t mp_obj_str_format(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kwa
894894
} else {
895895
if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
896896
terse_str_format_value_error();
897-
} else {
897+
} else if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL) {
898898
nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
899-
"end of format while looking for conversion specifier"));
899+
"bad conversion specifier"));
900+
} else {
901+
if (str >= top) {
902+
nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
903+
"end of format while looking for conversion specifier"));
904+
} else {
905+
nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
906+
"unknown conversion specifier %c", *str));
907+
}
900908
}
901909
}
902910
}
@@ -989,15 +997,9 @@ mp_obj_t mp_obj_str_format(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kwa
989997
mp_print_kind_t print_kind;
990998
if (conversion == 's') {
991999
print_kind = PRINT_STR;
992-
} else if (conversion == 'r') {
993-
print_kind = PRINT_REPR;
9941000
} else {
995-
if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
996-
terse_str_format_value_error();
997-
} else {
998-
nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
999-
"unknown conversion specifier %c", conversion));
1000-
}
1001+
assert(conversion == 'r');
1002+
print_kind = PRINT_REPR;
10011003
}
10021004
vstr_t arg_vstr;
10031005
mp_print_t arg_print;

tests/basics/string_format.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,13 @@ def test_fmt(conv, fill, alignment, sign, prefix, width, precision, type, arg):
140140
except ValueError:
141141
print('ValueError')
142142

143+
# end of format parsing conversion specifier
144+
try:
145+
'{!'.format('a')
146+
except ValueError:
147+
print('ValueError')
148+
149+
# unknown conversion specifier
143150
try:
144151
'abc{!d}'.format('1')
145152
except ValueError:
@@ -150,6 +157,7 @@ def test_fmt(conv, fill, alignment, sign, prefix, width, precision, type, arg):
150157
except ValueError:
151158
print('ValueError')
152159

160+
# expected ':' after specifier
153161
try:
154162
'{!s :}'.format(2)
155163
except ValueError:

0 commit comments

Comments
 (0)