A newbie quesiton: local variable in a nested funciton

Chris Angelico rosuav at gmail.com
Fri Dec 25 22:44:01 EST 2015


On Sat, Dec 26, 2015 at 2:06 PM,  <jfong at ms4.hinet.net> wrote:
> As a tranditional language programmer like me, the result is really weird.

By "traditional", I'm guessing you mean that you know C-like languages
(Java, ECMAScript/JavaScript, etc). In C, and in many languages
derived from or inspired by it, variable scoping is defined by
declarations that say "here begins a variable".

> Here is the test codes in file test1.py:
> --------
> def outerf():
>     counter = 55
>     def innerf():
>         print(counter)
>         #counter += 1
>     return innerf
>
> myf = outerf()

Pike is semantically very similar to Python, but it uses C-like
variable scoping. Here's an equivalent, which might help with
comprehension:

function outerf()
{
    int counter = 55;
    void innerf()
    {
        write("%d\n", counter);
        int counter;
        counter += 1;
    }
    return innerf;
}

Based on that, I think you can see that having a variable declaration
in the function turns things into nonsense. What you're actually
wanting here is to NOT have the "int counter;" line, such that the
name 'counter' refers to the outerf one.

In Python, assignment inside a function creates a local variable,
unless you declare otherwise. To make your example work, all you need
is one statement:

nonlocal counter

That'll cause the name 'counter' inside innerf to refer to the same
thing as it does in outerf.

Hope that helps!

ChrisA



More information about the Python-list mailing list