8000 py/lexer: Add support for underscores in numeric literals. · micropython/micropython@6a445b6 · GitHub
[go: up one dir, main page]

Skip to content

Commit 6a445b6

Browse files
committed
py/lexer: Add support for underscores in numeric literals.
This is a very convenient feature introduced in Python 3.6 by PEP 515.
1 parent b2fa1b5 commit 6a445b6

File tree

6 files changed

+36
-0
lines changed

6 files changed

+36
-0
lines changed

py/lexer.c

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -590,6 +590,8 @@ void mp_lexer_to_next(mp_lexer_t *lex) {
590590
}
591591
vstr_add_char(&lex->vstr, CUR_CHAR(lex));
592592
next_char(lex);
593+
} else if (is_char(lex, '_')) {
594+
next_char(lex);
593595
} else {
594596
break;
595597
}

py/parsenum.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,8 @@ mp_obj_t mp_parse_num_integer(const char *restrict str_, size_t len, int base, m
8383
mp_uint_t dig = *str;
8484
if ('0' <= dig && dig <= '9') {
8585
dig -= '0';
86+
} else if (dig == '_') {
87+
continue;
8688
} else {
8789
dig |= 0x20; // make digit lower-case
8890
if ('a' <= dig && dig <= 'z') {
@@ -273,6 +275,8 @@ mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool
273275
} else if (allow_imag && (dig | 0x20) == 'j') {
274276
imag = true;
275277
break;
278+
} else if (dig == '_') {
279+
continue;
276280
} else {
277281
// unknown character
278282
str--;

tests/basics/python36.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# tests for things that only Python 3.6 supports
2+
3+
# underscores in numeric literals
4+
print(100_000)
5+
print(0b1010_0101)
6+
print(0xff_ff)
7+
8+
# underscore supported by int constructor
9+
print(int('1_2_3'))
10+
print(int('0o1_2_3', 8))

tests/basics/python36.py.exp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
100000
2+
165
3+
65535
4+
123
5+
83

tests/float/python36.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# tests for things that only Python 3.6 supports, needing floats
2+
3+
# underscores in numeric literals
4+
print(1_000.1_8)
5+
print('%.2g' % 1e1_2)
6+
7+
# underscore supported by int/float constructors
8+
print(float('1_2_3'))
9+
print(float('1_2_3.4'))
10+
print('%.2g' % float('1e1_3'))

tests/float/python36.py.exp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
1000.18
2+
1e+12
3+
123.0
4+
123.4
5+
1e+13

0 commit comments

Comments
 (0)
0