Skip to content

Commit

Permalink
Merge pull request #176 from Terseus/bugfix/175-nonlocal-parameter
Browse files Browse the repository at this point in the history
Prevent incorrect syntax error with nonlocal of a parameter
  • Loading branch information
davidhalter authored Mar 8, 2021
2 parents 5bba083 + e5d6663 commit c4f297a
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
7 changes: 7 additions & 0 deletions parso/python/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,7 @@ def __init__(self, node, add_syntax_error, parent_context=None):
self.parent_context = parent_context
self._used_name_dict = {}
self._global_names = []
self._local_params_names = []
self._nonlocal_names = []
self._nonlocal_names_in_subscopes = []
self._add_syntax_error = add_syntax_error
Expand All @@ -264,6 +265,10 @@ def add_name(self, name):
self._global_names.append(name)
elif parent_type == 'nonlocal_stmt':
self._nonlocal_names.append(name)
elif parent_type == 'funcdef':
self._local_params_names.extend(
[param.name.value for param in name.parent.get_params()]
)
else:
self._used_name_dict.setdefault(name.value, []).append(name)

Expand Down Expand Up @@ -291,6 +296,8 @@ def finalize(self):
nonlocals_not_handled = []
for nonlocal_name in self._nonlocal_names_in_subscopes:
search = nonlocal_name.value
if search in self._local_params_names:
continue
if search in global_name_strs or self.parent_context is None:
message = "no binding for nonlocal '%s' found" % nonlocal_name.value
self._add_syntax_error(nonlocal_name, message)
Expand Down
7 changes: 7 additions & 0 deletions test/failing_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,13 @@ def y():
def z():
nonlocal a
'''),
# Name is assigned before nonlocal declaration
dedent('''
def x(a):
def y():
a = 10
nonlocal a
'''),
]

if sys.version_info[:2] >= (3, 7):
Expand Down
23 changes: 23 additions & 0 deletions test/normalizer_issue_files/allowed_syntax.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,29 @@ class z():
nonlocal a


def x(a):
def y():
nonlocal a


def x(a, b):
def y():
nonlocal b
nonlocal a


def x(a):
def y():
def z():
nonlocal a


def x():
def y(a):
def z():
nonlocal a


a = *args, *args
error[(*args, *args)] = 3
*args, *args

0 comments on commit c4f297a

Please sign in to comment.