PEP-343 - Context Managment variant

falcon falcon at intercable.ru
Fri Aug 5 02:26:26 EDT 2005


Sorry. I was wrong about "global" statement.
Then examples seems to be even more intricate:

def Synhronised(lock,func):
        lock.acquire()
        try:
                func()
        finally:
                lock.release()
....
lock=Lock()
def Here_I_work(*a): return 1 # Stub
def asd(a): return a          # Stub

def Some():
    local_var1=1
    local_var2=2
    local_var3=[None]
    def Work():
        local_var3[0]=Here_I_work(local_var1,local_var2,local_var3)
    Synhronised(lock,Work)
    return asd(local_var3[0])

FileOpenClose Example:

def FileOpenClose(name,mode,func):
    f=file(name,mode)
    try:
        func(f)
    finally:
        f.close()

....

def Another(name):
    local_var3=[None]
    def Work(f):
        local_var3[0]=[[x,y(i)] for i in f]
    FileOpenClose(name,'r',Work)
    return local_var3[0]

Here we must to declare local_var3 as array, though we using it as scalar.

Following is from previous letter (with correction). Please do not be severe, I'm not great programmer
and my English isn't A and even B graduated.

I think it is possible to introduce(internally) block-object in analogy to lambda-object
(and function-object).
It's difference from function:
   it has no true self local variables, all global(free) and local variables it steels from outter
   scope. And all local vars, introduced in block are really introduced in outter scope
   (i think, during parse state). So its global dicts and local dicts are realy corresponding dicts
   of outter scope (so, may be block call would be faster than function call. I don't know)

Syntax can be following:

lock=Lock()
def Some():
    local_var1=1
    local_var2=2
    local_var3=3
    Synhronised(lock,block):
        local_var3=Here_I_work(local_var1,local_var2,local_var3)
    return asd(local_var3)

def Another(name):
    FileOpenClose(name,'r',block{f}):
        local_var3=[[x,y(i)] for i in f]
    return local_var3


And here is sample of returning value:

def Foo(context,proc):
    context.enter()
    try:
        res=proc(context.x,context.y)*2
    except Exception,Err:
        context.throw(Err)
    finally:
        context.exit()
    return res
...
context=MyContext()
...
def Bar():
    result=Foo(context,block{x,y}):
        continue x+y
    return result

The idea was stolen from Ruby. My be it is not Pythonic.






More information about the Python-list mailing list