Skip to content

No binding for nonlocal | Solution examples

  • by

No binding for a nonlocal variable declared in a decorator

Variable is declared inside the returning() function before calling func(), yet getting a binding error.

def decorator(func):
    def returning():
        var = 1
        func()
        print(var)
    return(returning)
@decorator
def function():
    nonlocal var
    var = 5
function()

Output:

No binding for a nonlocal variable

Python determines scopes at compile time, making the scope model static, not dynamic. The nonlocal and global statements tell the compiler to alter the scope where a name is set. nonlocal tells the compiler that a given name is to be assigned to as a closure, living in an enclosing scope. See the Naming and binding section of the Python execution model documentation:

A source with Full answer: https://stackoverflow.com/questions/50051496/

Common No binding for nonlocal

“nonlocal” only works in nested functions. It’s possible you might want to use the “global” keyword instead, assuming you don’t actually have nested functions, but merely more functions.

Do comment if you have any doubts or suggestions on this Python Nonlocal.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *