Avoid `exc=None; del exc` in bytecode where unnecessary
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 36k
- PR merge metrics
- PR metrics pending
Description
See https://github.com/faster-cpython/ideas/issues/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
- PR: gh-99361
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked faster-cpython/ideas issue 490 and PR gh-99361, then inspect the Python compiler path that emits exception-handler cleanup bytecode. Use the dis(f) example as the baseline; done means omitting the unnecessary exc=None; del exc sequence where the exception variable is guaranteed to be bound without changing exception semantics.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Refactor
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 25/100