osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Variable scope in nested functions


On Tue, Jan 30, 2018 at 1:48 PM, Prahallad Achar <acharbly at gmail.com> wrote:
> def a() :
>     Print (value)
>     def b() :
>          Value = 100
>     Return b
>
> Its a nested function.  How can I use variable value just one function
> above the parent function.
> This is possible in tcl.. Is it possible in Python too?

It is. What you have is a "nonlocal" variable. You will need to assign
to the variable in the outer function though.

def a():
    value = None
    def b():
        nonlocal value
        value = 100
    return b

You can do this through any number of levels of nested functions.

ChrisA