ruff
da882b66 - F401 - Recommend adding unused import bindings to `__all__` (#11314)

Commit
1 year ago
F401 - Recommend adding unused import bindings to `__all__` (#11314) Followup on #11168 and resolve #10391 # User facing changes * F401 now recommends a fix to add unused import bindings to to `__all__` if a single `__all__` list or tuple is found in `__init__.py`. * If there are no `__all__` found in the file, fall back to recommending redundant-aliases. * If there are multiple `__all__` or only one but of the wrong type (non list or tuple) then diagnostics are generated without fixes. * `fix_title` is updated to reflect what the fix/recommendation is. Subtlety: For a renamed import such as `import foo as bees`, we can generate a fix to add `bees` to `__all__` but cannot generate a fix to produce a redundant import (because that would break uses of the binding `bees`). # Implementation changes * Add `name` field to `ImportBinding` to contain the name of the _binding_ we want to add to `__all__` (important for the `import foo as bees` case). It previously only contained the `AnyImport` which can give us information about the import but not the binding. * Add `binding` field to `UnusedImport` to contain the same. (Naming note: the field `name` field already existed on `UnusedImport` and contains the qualified name of the imported symbol/module) * Change `fix_by_reexporting` to branch on the size of `dunder_all: Vec<&Expr>` * For length 0 call the edit-producing function `make_redundant_alias`. * For length 1 call edit-producing function `add_to_dunder_all`. * Otherwise, produce no fix. * Implement the edit-producing function `add_to_dunder_all` and add unit tests. * Implement several fixture tests: empty `__all__ = []`, nonempty `__all__ = ["foo"]`, mis-typed `__all__ = None`, plus-eq `__all__ += ["foo"]` * `UnusedImportContext::Init` variant now has two fields: whether the fix is in `__init__.py` and how many `__all__` were found. # Other changes * Remove a spurious pattern match and instead use field lookups b/c the addition of a field would have required changing the unrelated pattern. * Tweak input type of `make_redundant_alias` --------- Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
Author
Parents
Loading