PEP-343 - Context Managment variant

Terry Reedy tjreedy at udel.edu
Thu Aug 4 14:41:50 EDT 2005


"falcon" <falcon at intercable.ru> wrote in message 
news:313379598.20050804110933 at intercable.ru...
> def Synhronised(lock,func):
>        lock.acquire()
>        try:
>                func()
>        finally:
>                lock.release()
> ....
> lock=Lock()
> def Some():
>    local_var1=x
>    local_var2=y
>    local_var3=Z
>    def Work():
>        global local_var3
>        local_var3=Here_I_work(local_var1,local_var2,local_var3)
>    Synhronised(lock,Work)
>    return asd(local_var3)

When posting code, I (try to remember to) either cut and paste code that 
works or label it as untested, imcomplete, hypothetical, pseudo, or 
somesuch.  The above will not work as posted because several names are 
undefined.

Even with that fixed, or bindings assumed, Work() will not work (and would 
not work as expected even if it did) because global statements have no 
connection with enclosed local variables.  Read 
http://docs.python.org/ref/global.html with the understanding that 
'globals' means the module global namespace as returned by globals(). 
Hence the attempt to read local_var3 as a global will raise a NameError 
(given the absence of a global binding) and the setting of local_var3 as a 
global will not affect the local variable of Some with the same name. 
Hence the latter would keep the original value Z even if things did work.

One possible revision (obviously not tested ;-): add
   local_var4 = [] # in the obvious place and rewrite the rest as
   def Work():
        local_var4[0] = Here.....
   Synchronized(...)
   return asd(local_var4[0])

> It was complicated because :
>    1. We must declare closure (local function)  before using it

You must create any object before you use it, and bind any name to some 
object before you ask for the object bound to that name.

>    2. We must declare local vars, to which we wish assign in "global" 
> statement

Wrong.  See above.  You cannot rebind enclosed local variables, only modify 
the associated object (if mutable, as in my suggested revision above).

>    3. We cannot create variable local to outter function in closure,
> so we must create it before and declare in [it] global

You can declare a currently unlocally bound name to be global but once you 
create a local variable (bind an object to a name in the local namespace, 
or give instructions for that to happen) you cannot just redeclare it to be 
global.

> So one can say: "that is because there're no block lambda". (I can be 
> wrong)

I stopped reading here, so have no further comment.

Terry J. Reedy






More information about the Python-list mailing list