[Python-Dev] Compilation of "except FooExc as var" adds useless store

Serhiy Storchaka storchaka at gmail.com
Sun Jan 6 10:26:09 EST 2019

06.01.19 13:10, Paul Sokolovsky пише:
> Storing None looks superfluous. For example, DELETE_FAST explicitly
> stores NULL on delete.
> https://github.com/python/cpython/blob/master/Python/ceval.c#L2249
> Likewise, for DELETE_NAME/DELETE_GLOBAL, PyObject_DelItem() is
> called which translates to:
> m->mp_ass_subscript(o, key, (PyObject*)NULL);
> So hopefully any compliant mapping implementation actually clears
> stored value, not leaving it dangling.
> The "store None" behavior can be traced down to introduction of the
> "del except target var" behavior back in 2007:
> https://github.com/python/cpython/commit/b940e113bf90ff71b0ef57414ea2beea9d2a4bc0#diff-cb296cc5109f5640ff3f6d7198a6abeeR1999
> There's no clear explanation why it's done like that, so probably an
> artifact of the initial implementation. Note that even
> https://github.com/python/cpython/commit/520b7ae27e39d1c77ea74ccd1b184d7cb43f9dcb
> which did quite a bunch of refactoring to "except" implementation, and
> reformatted this code, otherwise left it in place.

Because there is a reason for such code.

See issue1631942 [1] and the thread with the subject "self-contained 
exceptions" on the Python-3000 mailing list [2] for the rationale.

In short, the code

     except Exception as e:
         del e

should work.

I do not see a problem with storing None before deleting a variable. 
This is not a performance critical code, because it is executed only 
when an exception was raised and caught.

[1] https://bugs.python.org/issue1631942
[2] https://mail.python.org/pipermail/python-3000/2007-January/005294.html

More information about the Python-Dev mailing list