diff --git a/parso/python/normalizer.py b/parso/python/normalizer.py index 3965d23..60777ab 100644 --- a/parso/python/normalizer.py +++ b/parso/python/normalizer.py @@ -32,6 +32,11 @@ class WhitespaceInfo(object): self.trailing_whitespace = [] self.comment_whitespace = [] + +def _is_magic_name(name): + return name.value.startswith('__') and name.value.startswith('__') + + class PEP8Normalizer(Normalizer): def __init__(self, config): super(PEP8Normalizer, self).__init__(config) @@ -72,13 +77,30 @@ class PEP8Normalizer(Normalizer): break if typ in IMPORT_TYPES: - module = node.parent + simple_stmt = node.parent + module = simple_stmt.parent + #if module.type == 'simple_stmt': if module.type == 'file_input': - index = module.children.index(node) + index = module.children.index(simple_stmt) + from parso.python.tree import Flow for child in module.children[:index]: - if child.type not in IMPORT_TYPES: + children = [child] + if child.type == 'simple_stmt': + # Remove the newline. + children = child.children[:-1] + for c in children: + if c.type == 'expr_stmt' and \ + all(_is_magic_name(n) for n in c.get_defined_names()): + continue + + if c.type in IMPORT_TYPES or isinstance(c, Flow): + continue + self.add_issue(402, 'Module level import not at top of file', node) break + else: + continue + break if typ == 'suite': self.indentation += 1 diff --git a/test/normalizer_issue_files/E40.py b/test/normalizer_issue_files/E40.py new file mode 100644 index 0000000..5382f79 --- /dev/null +++ b/test/normalizer_issue_files/E40.py @@ -0,0 +1,39 @@ +#: E401:7 +import os, sys +# Okay +import os +import sys + +from subprocess import Popen, PIPE + +from myclass import MyClass +from foo.bar.yourclass import YourClass + +import myclass +import foo.bar.yourclass +# All Okay from here until the definition of VERSION +__all__ = ['abc'] + +import foo +__version__ = "42" + +import foo +__author__ = "Simon Gomizelj" + +import foo +try: + import foo +except ImportError: + pass +else: + print('imported foo') +finally: + print('made attempt to import foo') + +import bar +VERSION = '1.2.3' + +#: E402 +import foo +#: E402 +import foo diff --git a/test/normalizer_issue_files/E72.py b/test/normalizer_issue_files/E72.py index 0f99a09..c39cacc 100644 --- a/test/normalizer_issue_files/E72.py +++ b/test/normalizer_issue_files/E72.py @@ -33,6 +33,7 @@ assert type(res) is type((1, )) assert type(res) is not type((1, )) # Okay +#: E402 import types if isinstance(res, int):