KEMBAR78
nonlocal in class def reports an error. · Issue #12730 · python/mypy · GitHub
Skip to content

nonlocal in class def reports an error. #12730

@mrolle45

Description

@mrolle45

Bug Report

A class def containing a nonlocal declaration is flagged as an error, even though this is legal Python.

To Reproduce

X.py:

def f():
    a = 0
    class C:
        nonlocal a
        a = 1

mypy output:
error: nonlocal declaration not allowed at module level

Fix
Change one line in SemanticAnalyzer.visit_nonlocal_decl
from:

	def visit_nonlocal_decl(self, d: NonlocalDecl) -> None:
		self.statement = d
!		if not self.is_func_scope():
			self.fail("nonlocal declaration not allowed at module level", d)
		...

to:

	def visit_nonlocal_decl(self, d: NonlocalDecl) -> None:
		self.statement = d
!		if self.is_module_scope():
			self.fail("nonlocal declaration not allowed at module level", d)
		...

The error message now disappears. Note, it still appears at the module level, as it is a SyntaxError in Python.

Your Environment

  • Mypy version used: 0.931

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions