star-destroyer icon indicating copy to clipboard operation
star-destroyer copied to clipboard

Imports exception object used in `except` clause

Open romanlevin opened this issue 9 years ago • 5 comments

Given:

# a.py
e = 'something'

# b.py
from a import *

try:
    something()
except Exception as e:
    log(e)

Transforms

from a import *

into:

from a import e

romanlevin avatar Jun 27 '16 08:06 romanlevin

Yes, this happens because star_destroyer sees log(e) as a usage of e, and it is not smart enough to know for certain that a.e is always shadowed by the e in the except clause. To err on the side of safety, it preserves the import of e.

zestyping avatar Jun 27 '16 09:06 zestyping

That's very reasonable. and I understand that star_destroyer is at least partly meant in jest, but I thought this should still be documented and perhaps addressed later, if someone finds a good solution.

romanlevin avatar Jun 27 '16 10:06 romanlevin

Oh yes, I'd love for it to be smarter. Thanks for reporting this.

It is intended to be actually useful (even as it has room to improve). The design goal is to guarantee that running it on your code can never break your code, at the expense of possibly missing some opportunities to remove imports.

zestyping avatar Jun 27 '16 17:06 zestyping

It already is useful! I used it today at work to fix a hopeless-seeming situation with nested star imports at least four-deep.

It took me a couple of hours to disentangle the stdlib modules out of that and make sure we imported names from the module where they are actually defined (rather than some other module that imports and uses that name), but without your tool it would have taken me an entire day at least.

romanlevin avatar Jun 27 '16 18:06 romanlevin

Four levels! Ouch! Glad this helped. :)

zestyping avatar Jun 27 '16 18:06 zestyping