diff --git a/flake8_import_style/__init__.py b/flake8_import_style/__init__.py index 9782176..ff3b8aa 100644 --- a/flake8_import_style/__init__.py +++ b/flake8_import_style/__init__.py @@ -5,7 +5,7 @@ __version__ = pkg_resources.get_distribution(__package__).version -I801 = "I801 use 'import {module}' instead of 'from {module} import {names}'" +I801 = "I801 use 'import {stmt}' instead of 'from {module} import {names}'" class I8(object): @@ -22,7 +22,22 @@ def run(self): if isinstance(i, ast.ImportFrom): if i.module == "__future__": continue - message = I801.format( - module=(i.module or "..."), - names=", ".join(i.name for i in i.names)) + module = ("." * i.level) + (i.module or "") + names = ", ".join(i.name for i in i.names) + if i.module is None: + # Relative imports don't work with the `import <>` syntax. + message = I801.format( + stmt=names, + module=module, + names=names) + elif len(i.names) == 1: + message = I801.format( + stmt="{0}.{1}".format(i.module, names), + module=module, + names=names) + else: + message = I801.format( + stmt=i.module, + module=module, + names=names) yield (i.lineno, i.col_offset, message, "I801") diff --git a/flake8_import_style/tests/__init__.py b/flake8_import_style/tests/__init__.py index dcd7c2f..a771b9a 100644 --- a/flake8_import_style/tests/__init__.py +++ b/flake8_import_style/tests/__init__.py @@ -21,7 +21,7 @@ def test_run(self): self.assertEqual(list(i8.run()), [( 1, 0, - "I801 use 'import ...' instead of 'from ... import obj'", + "I801 use 'import obj' instead of 'from . import obj'", "I801", )]) @@ -30,7 +30,25 @@ def test_run(self): self.assertEqual(list(i8.run()), [( 1, 0, - "I801 use 'import ...' instead of 'from ... import obj'", + "I801 use 'import obj' instead of 'from .. import obj'", + "I801", + )]) + + tree = ast.parse("from ..mod import obj") + i8 = flake8_import_style.I8(tree) + self.assertEqual(list(i8.run()), [( + 1, + 0, + "I801 use 'import mod.obj' instead of 'from ..mod import obj'", + "I801", + )]) + + tree = ast.parse("from .mod import obj1, obj2") + i8 = flake8_import_style.I8(tree) + self.assertEqual(list(i8.run()), [( + 1, + 0, + "I801 use 'import mod' instead of 'from .mod import obj1, obj2'", "I801", )]) @@ -39,7 +57,16 @@ def test_run(self): self.assertEqual(list(i8.run()), [( 1, 0, - "I801 use 'import mod' instead of 'from mod import obj'", + "I801 use 'import mod.obj' instead of 'from mod import obj'", + "I801", + )]) + + tree = ast.parse("from mod import obj1, obj2") + i8 = flake8_import_style.I8(tree) + self.assertEqual(list(i8.run()), [( + 1, + 0, + "I801 use 'import mod' instead of 'from mod import obj1, obj2'", "I801", )])