How to modify local variables from internal functions?

Chris Rebert clp2 at rebertia.com
Fri Oct 23 20:23:34 EDT 2009


On Fri, Oct 23, 2009 at 5:19 PM, kj <no.email at please.post> wrote:
> I like Python a lot, and in fact I'm doing most of my scripting in
> Python these days, but one thing that I absolutely *****DETEST*****
> about Python is that it does allow an internal function to modify
> variables in the enclosing local scope.  This willful hobbling of
> internal functions seems to me so perverse and unnecessary that it
> delayed my adoption of Python by about a decade.  Just thinking
> about it brings me to the brink of blowing a gasket...  I must go
> for a walk...
<snip>
> Anyway, I recently wanted to write a internal helper function that
> updates an internal list and returns True if, after this update,
> the list is empty, and once more I bumped against this hated
> "feature".  What I wanted to write, if Python did what I wanted it
> to, was this:
>
> def spam():
>    jobs = None
>    def check_finished():
>       jobs = look_for_more_jobs()
>       return not jobs
>
>    if check_finished():
>        return
>
>    process1(jobs)
>
>    if check_finished():
>        return
>
>    process2(jobs)
>
>    if check_finished():
>        return
>
>    process3(jobs)
<snip>
> Is there some other trick to modify local variables from within
> internal functions?

The `nonlocal` statement?:
http://www.python.org/dev/peps/pep-3104/

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list