Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python inner functions

Tags:

python

In python, I can write :

def func():
    x = 1
    print x
    x+=1

    def _func():
        print x
    return _func

test = func()
test()

when I run it, the output is :

1

2

As _func has access to the "x" variable defined in func. Right...

But if I do :

def func():
    x = 1
    print x

    def _func():
        x+=1
        print x
    return _func

test = func()
test()

Then I got an error message : UnboundLocalError: local variable 'x' referenced before assignment

In this case, it seems that _func cannot "see" the "x" variable

The question is: Why does print x in the first example "see" the "x" variable, whereas the mathematical operator x+=1 throws an exception?

I don't understand why...

like image 610
espern Avatar asked Sep 04 '13 14:09

espern


1 Answers

Check this answer : https://stackoverflow.com/a/293097/1741450

Variables in scopes other than the local function's variables can be accessed, but can't be rebound to new parameters without further syntax. Instead, assignment will create a new local variable instead of affecting the variable in the parent scope. For example:

like image 194
lucasg Avatar answered Sep 18 '22 18:09

lucasg