Skip to content

SyntaxError from assignment to nonlocal or global variable. #51

@mrolle45

Description

@mrolle45

Bug Report:

When assigning to a nonlocal or global variable, the translation contains syntax errors, because these variables cannot be annotated.
Example

class C:
	global x
	x = 2 # type: int

This translates to

class C:
        global x
        x: int = 2

Running this results in

  File "t.py", line 3
    x: int = 2
    ^
SyntaxError: annotated name 'x' can't be global

Similar result if x is nonlocal rather than global.

What to do?

First of all, you need to find the global or nonlocal statement for the variable in its enclosing scope. Then you will know that the variable cannot be annotated at that point.
Next, decide how you want to handle it, and then implement it. Some possibilities are:

  • Output an error message, with the line number, variable name, and whether it is nonlocal or global. And/or just put it in the "comments skipped" message.
  • Remove the type comment and annotate x in the scope which owns x.
    For a global, this is at the module level.
    For a nonlocal, you have to search enclosing scopes to find the one where x is bound.
    In either case,
    • if x is assigned in the scope, just add the annotation to it.
    • Otherwise, add a bare annotation somewhere in the scope. It should probably be in the same control flow block, so that if the code is unreachable, then a type checker won't use the annotation either.

Some code that might be useful.

I am writing a package which performs analysis tasks related to scopes and namespaces in a python program. It is still a work in progress. However, there is already enough functionality that you could find useful, not only in fixing the present bug but for other tasks as well.
You can find it at mrolle45/scopetools. Please let me know if you find it interesting, and I'd like to work with you in incorporating my code into your code.
scopetools will create a tree of Scope objects representing the scopes found in the ast.Module tree. The Scope will give you the status of a variable name including which Scope actually owns it. It also points to the ast object for that scope, so you can traverse it. I plan to provide a method to traverse the ast omitting any nested scopes. That way, you can discover all the type comments in the module and the scopes that contain them.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions