Black: Should black remove unused imports?

Created on 29 Mar 2018  路  7Comments  路  Source: psf/black

I've noticed that right now Black doesn't do that.
I'm wondering whether it's something that Black should take care of?

design enhancement wontfix

Most helpful comment

I'm afraid this is scope creep and something that can silently break otherwise valid programs. My intuition is to avoid this in Black.

All 7 comments

+1

There is already a tool that does that, btw.: https://github.com/myint/autoflake

I'm afraid this is scope creep and something that can silently break otherwise valid programs. My intuition is to avoid this in Black.

Javascript has the same issue and Prettier doesn't seem to have the same qualm in removing unused imports and vars by default. Is there anything special in Python that you can't do with ES modules?

Imports has some weird side effects sometimes that would probably be really hard to detect statically. See the example here
https://github.com/psf/black/issues/333#issuecomment-461803520. The example is a valid set of instructions per se, but it depends on an side effect of importing. Even if pkg.mod2 doesn't seemed to be used, it is needed so the REPL can access pkg.mod which is imported via pkg.mod2.

I see. I guess __all__ = [foo, bar] will also make it hard too, since now you have to chase an entire graph to dereference the values too.

Imports has some weird side effects sometimes that would probably be really hard to detect statically. See the example here
#333 (comment). The example is a valid set of instructions per se, but it depends on an side effect of importing. Even if pkg.mod2 doesn't seemed to be used, it is needed so the REPL can access pkg.mod which is imported via pkg.mod2.

I agree with you!

BTW, I've developed a tool to do this task safely, If you are interested please check it out!

Docs: https://hadialqattan.github.io/pycln
Repo: https://github.com/hadialqattan/pycln

Was this page helpful?
0 / 5 - 0 ratings