Skip to content

Commit b1533c4

Browse files
committed
py/parse: Treat constants that start with underscore as private.
Assignments of the form "_id = const(value)" are treated as private (following a similar CPython convention) and code is no longer emitted for the assignment to a global variable. See issue adafruit#2111.
1 parent 2bf6eb9 commit b1533c4

3 files changed

Lines changed: 26 additions & 0 deletions

File tree

py/parse.c

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -461,6 +461,8 @@ STATIC const mp_rom_map_elem_t mp_constants_table[] = {
461461
STATIC MP_DEFINE_CONST_MAP(mp_constants_map, mp_constants_table);
462462
#endif
463463

464+
STATIC void push_result_rule(parser_t *parser, size_t src_line, const rule_t *rule, size_t num_args);
465+
464466
#if MICROPY_COMP_CONST_FOLDING
465467
STATIC bool fold_constants(parser_t *parser, const rule_t *rule, size_t num_args) {
466468
// this code does folding of arbitrary integer expressions, eg 1 + 2 * 3 + 4
@@ -587,6 +589,15 @@ STATIC bool fold_constants(parser_t *parser, const rule_t *rule, size_t num_args
587589
assert(elem->value == MP_OBJ_NULL);
588590
elem->value = MP_OBJ_NEW_SMALL_INT(value);
589591

592+
// If the constant starts with an underscore then treat it as a private
593+
// variable and don't emit any code to store the value to the id.
594+
if (qstr_str(id)[0] == '_') {
595+
pop_result(parser); // pop const(value)
596+
pop_result(parser); // pop id
597+
push_result_rule(parser, 0, rules[RULE_pass_stmt], 0); // replace with "pass"
598+
return true;
599+
}
600+
590601
// replace const(value) with value
591602
pop_result(parser);
592603
push_result_node(parser, pn_value);

tests/micropython/const.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,15 @@ def f():
99
print(X, Y + 1)
1010

1111
f()
12+
13+
_X = const(12)
14+
_Y = const(_X + 34)
15+
16+
print(_X, _Y)
17+
18+
class A:
19+
Z = const(1)
20+
_Z = const(2)
21+
print(Z, _Z)
22+
23+
print(hasattr(A, 'Z'), hasattr(A, '_Z'))

tests/micropython/const.py.exp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,5 @@
11
123 580
22
123 580
3+
12 46
4+
1 2
5+
True False

0 commit comments

Comments
 (0)