Visitar URL original
Avoid `exc=None; del exc` in bytecode where unnecessary · Issue #99360 · python/cpython · GitHub
The Wayback Machine - https://web.archive.org/web/20260331144847/https://github.com/python/cpython/issues/99360
Skip to content
/ cpython Public

Avoid exc=None; del exc in bytecode where unnecessary #99360

@sweeneyde

Description

@sweeneyde

See faster-cpython/ideas#490.

To break reference cycles, the compiler has an implicit del e at the end of an exception handler. To make UnboundLocalErrors impossible during that deletion, the compiler adds e=None; del e instead.

However, the e=None part is unnecessary in many situations, namely, when we can prove that e is guaranteed to be bound (almost always!).

This can reduce the size of some bytecode objects. For example, the four <---- lines below can be deleted:

>>> def f():
...     try: pass
...     except Exception as e: pass
...
>>> dis(f)
  1           0 RESUME                   0

  2           2 LOAD_CONST               0 (None)
              4 RETURN_VALUE
              6 PUSH_EXC_INFO

  3           8 LOAD_GLOBAL              0 (Exception)
             20 CHECK_EXC_MATCH
             22 POP_JUMP_IF_FALSE       11 (to 46)
             24 STORE_FAST               0 (e)
             26 POP_EXCEPT
             28 LOAD_CONST               0 (None)  <---------
             30 STORE_FAST               0 (e)     <---------
             32 DELETE_FAST              0 (e)     
             34 LOAD_CONST               0 (None)
             36 RETURN_VALUE
             38 LOAD_CONST               0 (None)  <---------
             40 STORE_FAST               0 (e)     <---------
             42 DELETE_FAST              0 (e)
             44 RERAISE                  1
        >>   46 RERAISE                  0
        >>   48 COPY                     3
             50 POP_EXCEPT
             52 RERAISE                  1
ExceptionTable:
  6 to 24 -> 48 [1] lasti
  38 to 46 -> 48 [1] lasti

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.13bugs and security fixesinterpreter-core(Objects, Python, Grammar, and Parser dirs)performancePerformance or resource usagetype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions