[Python-Dev] PEP-343 - Context Managment variant

falcon falcon at intercable.ru
Thu Aug 4 09:09:33 CEST 2005


I know I came after the battle. And I have just another sight on context managment.

Simple Context Managment may look in Python 2.4.1 like this:

Synhronized example:

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)

FileOpenClose Example:

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

....

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

It was complicated because :
    1. We must declare closure (local function)  before using it
    2. We must declare local vars, to which we wish assign in "global" statement
    3. We cannot create variable local to outter function in closure, so we must create it before
       and declare in global
So one can say: "that is because there're no block lambda". (I can be wrong)
I think it is possible to introduce 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. (Excuse my english)
So, may be it would be faster than function call. I don't know.

Syntax can be following:

lock=Lock()
def Some():
    local_var1=x
    local_var2=y
    local_var3=Z
    Synhronised(lock,block)
        local_var3=Here_I_work(local_var1,local_var2,local_var3)
    return asd(local_var3)

def Another(name):
    local_var1=x
    local_var2=y
    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

It's idea was token from Ruby. But I think, good idea is good whatever it came from.
It can be not Pythonic.




More information about the Python-Dev mailing list