Home > Software engineering >  Function within function to change a variable value
Function within function to change a variable value

Time:01-01

Why doesn't the variable url change?

def test():
    url = "Start"

    def change():
        global url
        url = "End"

    change()
    print(url)

    return url

test()

And yes, it needs to be a function within a function. That way the rest of my code is more simple. Thanks for your help!

CodePudding user response:

Global variables are those defined at the top-level scope of a module, not just any variable defined outside the scope of a function. The variable defined in test is a nonlocal variable from change's perspective, not a global variable.

Use the nonlocal keyword instead:

def test():
    url = "Start"

    def change():
        nonlocal url
        url = "End"

    change()
    print(url)

    return url

nonlocal causes the assignment to take place in the enclosing scope, creating the variable if necessary.


In your original function, change really does set (or even create) a global variable named url. For example:

def test():
    url = "Start"

    def change():
        global url
        url = "End"

    change()
    print(url)

    return url

try:
    print(url)
except NameError:
    print("'url' not yet defined")

test()  # Outputs "Start"
print(url)  # Outputs "End"

CodePudding user response:

The solution is to use the nonlocal keyword

def test():
    url = "Start"
    def change():
        nonlocal url
        url = "End"

    change()
    print(url)

    return url
  • Related