osdir.com


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

Variable scope in nested functions


Thanks Chris,
Without using nonlocal any other options available?

On 30 Jan 2018 8:30 am, "Chris Angelico" <rosuav at gmail.com> wrote:

> 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
> --
> https://mail.python.org/mailman/listinfo/python-list
>