summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorIan Lee <IanLee1521@gmail.com>2014-12-15 19:01:29 -0800
committerIan Lee <IanLee1521@gmail.com>2014-12-20 18:54:58 -0800
commit373e0ac1138f0e24422b5e2e78f02ed0557d5c23 (patch)
treedb0f7bbf16a3ae3579a1c4e358d2b2e2b6b2e14e
parent53d4741dbae96d0435fd8c55176611cc38816369 (diff)
downloadpep8-373e0ac1138f0e24422b5e2e78f02ed0557d5c23.tar.gz
Allow try/except/else/finally keywords intermixed with imports. #304
* This allows use of conditional imports. * Also move `__version__` definition to conform with this rule.
-rwxr-xr-xpep8.py15
1 files changed, 9 insertions, 6 deletions
diff --git a/pep8.py b/pep8.py
index 914d7fd..920213a 100755
--- a/pep8.py
+++ b/pep8.py
@@ -47,8 +47,6 @@ W warnings
"""
from __future__ import with_statement
-__version__ = '1.6.0a0'
-
import os
import sys
import re
@@ -64,6 +62,8 @@ try:
except ImportError:
from ConfigParser import RawConfigParser
+__version__ = '1.6.0a0'
+
DEFAULT_EXCLUDE = '.svn,CVS,.bzr,.hg,.git,__pycache__,.tox'
DEFAULT_IGNORE = 'E123,E226,E24,E704'
try:
@@ -850,7 +850,8 @@ def module_imports_on_top_of_file(
Okay: # this is a comment\nimport os
Okay: '''this is a module docstring'''\nimport os
Okay: r'''this is a module docstring'''\nimport os
- Okay: __version__ = "123"\nimport os
+ Okay: try:\n import x\nexcept:\n pass\nelse:\n pass\nimport y
+ Okay: try:\n import x\nexcept:\n pass\nfinally:\n pass\nimport y
E402: a=1\nimport os
E402: 'One string'\n"Two string"\nimport os
E402: a=1\nfrom sys import x
@@ -864,6 +865,8 @@ def module_imports_on_top_of_file(
line = line[1:]
return line and (line[0] == '"' or line[0] == "'")
+ allowed_try_keywords = ('try', 'except', 'else', 'finally')
+
if indent_level: # Allow imports in conditional statements or functions
return
if not logical_line: # Allow empty lines or comments
@@ -874,9 +877,9 @@ def module_imports_on_top_of_file(
if line.startswith('import ') or line.startswith('from '):
if checker_state.get('seen_non_imports', False):
yield 0, "E402 import not at top of file"
- elif line.startswith('__version__ '):
- # These lines should be included after the module's docstring, before
- # any other code, separated by a blank line above and below.
+ elif any(line.startswith(kw) for kw in allowed_try_keywords):
+ # Allow try, except, else, finally keywords intermixed with imports in
+ # order to support conditional importing
return
elif is_string_literal(line):
# The first literal is a docstring, allow it. Otherwise, report error.