Allow specific __future__ imports in modules

We do want to allow certain from __future__ imports in modules that make
it easier to code compatible python2 and python3.  Note that
unicode_literals is specifically left out and should never be allowed.
Now that python-3.4+ allows u"" there's no good reason to use
unicode_literals.

Also switch tables in the validate_modules documentation to simple table format
This commit is contained in:
Toshio Kuratomi 2017-07-27 03:37:32 -07:00
commit 3a2670e0fd
2 changed files with 95 additions and 120 deletions

View file

@ -225,6 +225,8 @@ class ModuleValidator(Validator):
'setup.ps1'
))
WHITELIST_FUTURE_IMPORTS = frozenset(('absolute_import', 'division', 'print_function'))
def __init__(self, path, analyze_arg_spec=False, base_branch=None, git_cache=None, reporter=None):
super(ModuleValidator, self).__init__(reporter=reporter or Reporter())
@ -558,6 +560,20 @@ class ModuleValidator(Validator):
for child in self.ast.body:
if isinstance(child, (ast.Import, ast.ImportFrom)):
if isinstance(child, ast.ImportFrom) and child.module == '__future__':
# allowed from __future__ imports
for future_import in child.names:
if future_import.name not in self.WHITELIST_FUTURE_IMPORTS:
self.reporter.error(
path=self.object_path,
code=209,
msg=('Only the following from __future__ imports are allowed: %s'
% ', '.join(self.WHITELIST_FUTURE_IMPORTS)),
line=child.lineno
)
break
else: # for-else. If we didn't find a problem nad break out of the loop, then this is a legal import
continue
import_lines.append(child.lineno)
if child.lineno < min_doc_line:
self.reporter.error(