zestyping / star-destroyer

Eliminates "import *" from your modules.
Apache License 2.0
37 stars 2 forks source link

Imports exception object used in `except` clause #6

Open romanlevin opened 8 years ago

romanlevin commented 8 years ago

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
zestyping commented 8 years ago

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.

romanlevin commented 8 years ago

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.

zestyping commented 8 years ago

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.

romanlevin commented 8 years ago

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.

zestyping commented 8 years ago

Four levels! Ouch! Glad this helped. :)