Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #11312: nonlocal does not raise SyntaxError #11382

Merged
merged 3 commits into from Oct 10, 2018
Merged
Changes from all commits
Commits
File filter...
Filter file types
Jump to…
Jump to file or symbol
Failed to load files and symbols.

Always

Just for now

@@ -97,14 +97,22 @@ class _AsyncSyntaxErrorVisitor(ast.NodeVisitor):
the implementation involves wrapping the repl in an async function, it
is erroneously allowed (e.g. yield or return at the top level)
"""
def __init__(self):
self.depth = 0
super().__init__()

def generic_visit(self, node):
func_types = (ast.FunctionDef, ast.AsyncFunctionDef)
invalid_types = (ast.Return, ast.Yield, ast.YieldFrom)

if isinstance(node, func_types):
return # Don't recurse into functions
elif isinstance(node, invalid_types):
invalid_types_by_depth = {
0: (ast.Return, ast.Yield, ast.YieldFrom),
1: (ast.Nonlocal,)
}

should_traverse = self.depth < max(invalid_types_by_depth.keys())
if isinstance(node, func_types) and should_traverse:
self.depth += 1
super().generic_visit(node)
elif isinstance(node, invalid_types_by_depth[self.depth]):
raise SyntaxError()
else:
super().generic_visit(node)
@@ -227,6 +227,35 @@ def nest_case(context, case):
else:
iprc(cell)

def test_nonlocal(self):
# fails if outer scope is not a function scope or if var not defined
with self.assertRaises(SyntaxError):
iprc("nonlocal x")
iprc("""
x = 1
def f():
nonlocal x
x = 10000
yield x
""")
iprc("""
def f():
def g():
nonlocal x
x = 10000
yield x
""")

# works if outer scope is a function scope and var exists
iprc("""
def f():
x = 20
def g():
nonlocal x
x = 10000
yield x
""")


def test_execute(self):
iprc("""
ProTip! Use n and p to navigate between commits in a pull request.
You can’t perform that action at this time.