Commit 013958ca authored by Bryton Lacquement's avatar Bryton Lacquement 🚪

New fixer: nested_except_trace

parent 5c7d51d8
from my2to3.fixes import BaseFix
from my2to3.trace import create_table
trace = create_table("nested_except", "filename", "lineno_parent", "lineno_child")
class FixNestedExceptTrace(BaseFix):
"""This fixer detects scope bugs which can occur due to nested except clauses
which use the same variable name.
Try the following code yourself in Python 2 and Python 3...
try:
raise Exception("foo")
except Exception as e:
try:
raise Exception("bar")
except Exception as e:
print(e)
print(e)
"""
# https://github.com/python/cpython/blob/3549ca313a6103a3adb281ef3a849298b7d7f72c/Lib/lib2to3/fixes/fix_except.py#L39-L45
PATTERN = """
try_stmt< 'try' ':' (simple_stmt | suite)
cleanup=(except_clause ':' (simple_stmt | suite))+
tail=(['except' ':' (simple_stmt | suite)]
['else' ':' (simple_stmt | suite)]
['finally' ':' (simple_stmt | suite)]) >
"""
order = "pre"
def start_tree(self, tree, filename):
super(FixNestedExceptTrace, self).start_tree(tree, filename)
# Store the results of every node that matches the pattern
self.results = []
def find_parents_results(self, node):
parents_results = []
parent = node.parent
while parent is not None:
for r in self.results:
if r['node'] is parent:
parents_results.append(r)
parent = parent.parent
return parents_results
def transform(self, node, results):
self.results.append(results)
# Find if the current node has parents, which are also a try_stmt
for parent_results in self.find_parents_results(node):
# Check if the node and its parent use the same variable name for the
# caught exception
parent_exception_node = parent_results['cleanup'][0]
exception_node = results['cleanup'][0]
try:
if exception_node.children[3] == parent_exception_node.children[3]:
trace(self.filename, parent_exception_node.get_lineno(), exception_node.get_lineno())
except Exception:
pass
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment