ruff icon indicating copy to clipboard operation
ruff copied to clipboard

Add fix to remove unused standard library imports from `__init__.py` files

Open zanieb opened this issue 1 year ago • 7 comments

See https://github.com/astral-sh/ruff/issues/10365#issuecomment-1995132836

We currently do not offer any fixes for unused imports in __init__.py files.

This issue is to fix standard library imports by removing them from the file. We should probably label this fix as unsafe.

zanieb avatar Mar 13 '24 17:03 zanieb

For the purposes of this check, I'm going to consider from __future__ import ... style imports to be "standard library".

plredmond avatar Apr 24 '24 21:04 plredmond

I think from __future__ imports can just be ignored entirely, since they should never be removed as "unused".

charliermarsh avatar Apr 25 '24 00:04 charliermarsh

Considered together with #10391, does this summary of behaviors seem right?

Old table
for some unused import... 

future                            → no diagnostic or fix
stdlib ∧  in_init                 → unsafe, remove
stdlib ∧ ¬in_init                 → safe,   remove
1stpty ∧  in_init                 → safe,   move to __all__ or convert to explicit-import
1stpty ∧ ¬in_init                 → safe,   remove
3rdpty ∧  in_init ∧  ignore_init  → no diagnostic or fix
3rdpty ∧  in_init ∧ ¬ignore_init  → unsafe, remove
3rdpty ∧ ¬in_init                 → safe,   remove

plredmond avatar Apr 25 '24 00:04 plredmond

My impression was that for 3rdpty ∧ in_init, we never offered a fix.

charliermarsh avatar Apr 25 '24 00:04 charliermarsh

That summary looks reasonable to me, with the addition that we should probably deprecate and remove the ignore_init option and remove third-party imports by default?

zanieb avatar Apr 25 '24 00:04 zanieb

Yeah I revise my comment -- what Zanie says sounds right.

charliermarsh avatar Apr 25 '24 00:04 charliermarsh

Ok, I've collapsed the table above. Here's an edited version without the ignore_init bit. I'll implement this, and try to make it flexible enough that I can PR #10390 separately from #10391 and so that we can more easily make changes to it in the future if desired.

for some unused import... 

future             → no diagnostic or fix
stdlib ∧  in_init  → unsafe, remove
stdlib ∧ ¬in_init  → safe,   remove
1stpty ∧  in_init  → safe,   move to __all__ or convert to explicit-import
1stpty ∧ ¬in_init  → safe,   remove
3rdpty ∧  in_init  → unsafe, remove
3rdpty ∧ ¬in_init  → safe,   remove

plredmond avatar Apr 25 '24 16:04 plredmond