Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I ran into an issue with an inner function I wrote regarding variable scope. I've managed to simply the code down to point to the exact problem. So starting with:

def outer(foo):

    def inner(bar):

        print(foo)

        print(bar)

    return inner 

if __name__ == "__main__":

    function = outer("foo")

    function("bar")

I'll get the expected output of :

foo

bar 

However, if I try and re-assign foo, I get an error:

def outer(foo):

    def inner(bar):

        foo = "edited " + foo

        print(foo)

        print(bar)

    return inner

Which gives:

UnboundLocalError: local variable 'foo' referenced before assignment  

This reminds me of globals, where you can "read" them normally but to "write" you have to do "global variable; variable=...". Is it the same situation? If so, is there a keyword that allows modification of foo from within inner?

1 Answer

0 votes
by (25.1k points)

To answer you question "is there a keyword that allows modification of foo from within inner", Yes there is. You can use the nonlocal keyword for this. Like this:

def outer(foo):

    def inner(bar):

        nonlocal foo

        foo = "edited " + foo

        print(foo)

        print(bar)

    return inner

outer("foo")("bar")

Related questions

0 votes
4 answers
0 votes
1 answer
0 votes
1 answer

Browse Categories

...