PEP-343 - Context Managment variant

F

falcon

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,021
Latest member
AkilahJaim

Latest Threads

Top