Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mark imports in __all__ as used #282

Merged
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
* Add whitelist for `pint.UnitRegistry.default_formatter` (Ben Elliston, #258).
* Mark imports in `__all__` as used (kreathon, #172).

# 2.4 (2022-05-19)

Expand Down
21 changes: 21 additions & 0 deletions tests/test_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,27 @@ def test_import_alias_use_alias(v):
check(v.unused_vars, [])


def test_import_with__all__(v):
v.scan(
"""\
# define.py
class Foo:
pass

class Bar:
pass

# main.py
from define import Foo, Bar

__all__ = ["Foo"]

"""
)
check(v.defined_imports, ["Foo", "Bar"])
check(v.unused_imports, ["Bar"])


def test_ignore_init_py_files(v):
v.scan(
"""\
Expand Down
17 changes: 17 additions & 0 deletions vulture/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@ def _is_test_file(filename):
)


def _assigns_special_variable__all__(node):
assert isinstance(node, ast.Assign)
name_targets = {
target.id for target in node.targets if isinstance(target, ast.Name)
}
return "__all__" in name_targets and isinstance(
node.value, (ast.List, ast.Tuple)
)
kreathon marked this conversation as resolved.
Show resolved Hide resolved


def _ignore_class(filename, class_name):
return _is_test_file(filename) and "Test" in class_name

Expand Down Expand Up @@ -616,6 +626,13 @@ def visit_Name(self, node):
elif isinstance(node.ctx, (ast.Param, ast.Store)):
self._define_variable(node.id, node)

def visit_Assign(self, node):
if _assigns_special_variable__all__(node):
assert isinstance(node.value, (ast.List, ast.Tuple))
for elt in node.value.elts:
if isinstance(elt, ast.Str):
self.used_names.add(elt.s)

def visit_While(self, node):
self._handle_conditional_node(node, "while")

Expand Down