<p dir="ltr"><br>
On 29 Jun 2013 10:38, <<a href="mailto:cts.private.yahoo@gmail.com">cts.private.yahoo@gmail.com</a>> wrote:<br>
><br>
> Hi,<br>
><br>
> I'd like to use closures to set allow a subroutine to set variables in its caller, in leu of pointers.  But I can't get it to work.  I have the following test pgm, but I can't understand its behaviour:<br>

><br>
> It uses a function p2() from the module modules.closure1b:<br>
><br>
>   def p2 (proc):<br>
>     proc ("dolly")<br>
><br>
> I thought the following worked like I expected it to:<br>
><br>
><br>
> from modules.closures1b import p2<br>
><br>
> def p1(msg1):<br>
>     msg3 = "world"<br>
>     print "p1: entered: ", msg1<br>
>     def p11(msg2):<br>
>         print "p11: entered: ", msg2<br>
>         print msg1 + msg2 + msg3<br>
>     print p2 (p11)<br>
><br>
> p1('hello')<br>
><br>
> $ python closures1c.py<br>
> p1: entered:  hello<br>
> p11: entered:  dolly<br>
> hellodollyworld<br>
> None<br>
><br>
> In other words, p1() is passed "hello" for msg1, "world" goes to the local msg3 and then p11() is invoked out of a remote module and it can access not only its own argument (msg2) but also the variables local to p1(): "hellodollyworld".<br>

><br>
> But if I try to set the variable local to p1(), all of a sudden python seems to forget everything we agreed on.<br>
><br>
> If I add this line to the script above:<br>
>         msg3 = "goodbye"<br>
> as follows:<br>
><br>
> from modules.closures1b import p2<br>
><br>
> def p1(msg1):<br>
>     msg3 = "world"<br>
>     print "p1: entered: ", msg1<br>
>     def p11(msg2):<br>
>         print "p11: entered: ", msg2<br>
>         print msg1 + msg2 + msg3<br>
>         msg3 = "goodbye"          # <- new<br>
>     print p2 (p11)<br>
><br>
> p1('hello')<br>
><br>
> then all of a sudden, I get this:<br>
><br>
> p1: entered:  hello<br>
> p11: entered:  dolly<br>
> Traceback (most recent call last):<br>
>   File "closures1c.py", line 13, in <module><br>
>     p1('hello')<br>
>   File "closures1c.py", line 11, in p1<br>
>     print p2 (p11)<br>
>   File "/home/mellman/eg/python/modules/closures1b.py", line 2, in p2<br>
>     proc ("dolly")<br>
>   File "closures1c.py", line 9, in p11<br>
>     print msg1 + msg2 + msg3<br>
> UnboundLocalError: local variable 'msg3' referenced before assignment<br>
><br>
><br>
> Huh?  msg3 isn't more referenced than it was before!<br>
><br>
> Can anyone explain this to me?</p>
<p dir="ltr">The fact that msg3 is assigned to in that scope makes it a local variable. It doesn't matter if the assignment happens later. Python will treat it as local, and so won't look for it outside the local scope/closure.</p>

<p dir="ltr">The fix is to declare msg3 as global, I think.</p>