Skip to content

Commit

Permalink
py/compile: Optimize code generated for "except Exc as var:".
Browse files Browse the repository at this point in the history
When such a clause is used (unlike just "except Exc:"), CPython wraps
exception handler body in try-finally block, and in the finally part,
executes "var = None; del var". The initial assignments appears to be
superfluous with the successive "del". It's there only to cover a case
when exeception handler would contain "del var" itself. Thus, compiler-
generated code would recreate the var and then delete again, to avoid
any spurious exception. Such a code would be rare, so avoid generating
assignment unless MICROPY_CPYTHON_COMPAT is defined.

Change-Id: I9a71821e394f87ff4153ae7c016e7d300147c429
  • Loading branch information
pfalcon committed Jan 23, 2019
1 parent e657ada commit ace947d
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions py/compile.c
Original file line number Diff line number Diff line change
Expand Up @@ -1595,8 +1595,16 @@ STATIC void compile_try_except(compiler_t *comp, mp_parse_node_t pn_body, int n_
if (qstr_exception_local != 0) {
EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE);
EMIT_ARG(label_assign, l3);
#if MICROPY_CPYTHON_COMPAT
// This follows CPython, and the only reason for this store is
// to allow code like:
// except Exc as foo:
// del foo
// That's quite a rare case, so save 2 bytecode bytes unless
// full CPython compatibility is requested.
EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE);
compile_store_id(comp, qstr_exception_local);
#endif
compile_delete_id(comp, qstr_exception_local);

compile_decrease_except_level(comp);
Expand Down

0 comments on commit ace947d

Please sign in to comment.