Add H203: Check for Python 3.x compatible except

Python 3.x deprecated 'except x,y:'
Enforce 'except x as y:' instead.

Change-Id: I0bd89fa05d88de34ca62ce59f427468ede226126
This commit is contained in:
Dirk Mueller 2013-06-01 16:37:26 +02:00
parent 80664dd471
commit ea077fb5fb
3 changed files with 44 additions and 1 deletions

@ -210,6 +210,25 @@ Example::
LOG.error(msg % {"s_id": "1234", "m_key": "imageId"})
Python 3.x compatibility
------------------------
OpenStack code should become Python 3.x compatible. That means all Python 2.x-only
constructs or dependencies should be avoided. An example is
except x,y:
Use
except x as y:
instead. Other Python 3.x compatility issues, like e.g. print operator
can be avoided in new code by using
from __future__ import print_function
at the top of your module.
Creating Unit Tests
-------------------
For every new feature, unit tests should be created that both test and

@ -214,6 +214,29 @@ def hacking_except_format_assert(logical_line):
yield 1, "H202: assertRaises Exception too broad"
@flake8ext
def hacking_except_python3x_compatible(logical_line):
r"""Check for except statements to be Python 3.x compatible
As of Python 3.x, the construct 'except x,y:' has been removed.
Use 'except x as y:' instead.
Okay: try:\n pass\nexcept Exception:\n pass
Okay: try:\n pass\nexcept (Exception, AttributeError):\n pass
H203: try:\n pass\nexcept AttributeError, e:\n pass
"""
def is_old_style_except(logical_line):
return (',' in logical_line
and ')' not in logical_line.rpartition(',')[2])
if (logical_line.startswith("except ")
and logical_line.endswith(':')
and is_old_style_except(logical_line)):
yield 0, "H203: Python 3.x incompatible 'except x,y:' construct"
modules_cache = dict((mod, True) for mod in tuple(sys.modules.keys())
+ sys.builtin_module_names)
@ -266,7 +289,7 @@ def hacking_import_rules(logical_line, filename):
try:
# NOTE(vish): handle namespace modules
__import__(mod)
except ImportError, exc:
except ImportError as exc:
# NOTE(vish): the import error might be due
# to a missing dependency
missing = str(exc).split()[-1]

@ -31,6 +31,7 @@ flake8.extension =
H102 = hacking.core:hacking_has_license
H201 = hacking.core:hacking_except_format
H202 = hacking.core:hacking_except_format_assert
H203 = hacking.core:hacking_except_python3x_compatible
H301 = hacking.core:hacking_import_rules
H306 = hacking.core:hacking_import_alphabetical
H401 = hacking.core:hacking_docstring_start_space