[Assorted-commits] SF.net SVN: assorted:[912] sandbox/trunk/src/py/with_decorator.py
Brought to you by:
yangzhang
From: <yan...@us...> - 2008-07-30 02:08:27
|
Revision: 912 http://assorted.svn.sourceforge.net/assorted/?rev=912&view=rev Author: yangzhang Date: 2008-07-30 02:08:37 +0000 (Wed, 30 Jul 2008) Log Message: ----------- added demo that with cannot be implemented in python 2.4 Added Paths: ----------- sandbox/trunk/src/py/with_decorator.py Added: sandbox/trunk/src/py/with_decorator.py =================================================================== --- sandbox/trunk/src/py/with_decorator.py (rev 0) +++ sandbox/trunk/src/py/with_decorator.py 2008-07-30 02:08:37 UTC (rev 912) @@ -0,0 +1,45 @@ +# Can we implement the with statement using decorators? Not really.... + +class ctxmgr(object): pass # not used + +def With(ctx): + def wrapper(func): + if type(ctx) == ctxmgr: + rsrc = ctx.enter() + if func.func_code.co_argcount == 0: result = func() + else: result = func(rsrc) + ctx.exit() + elif type(ctx).__name__ == 'generator': + rsrc = ctx.next() + if func.func_code.co_argcount == 0: result = func() + else: result = func(rsrc) + else: assert False, type(ctx) + return result + return wrapper + +# some context managers + +def closing(rsrc): + try: yield rsrc + finally: print 'CLOSIN'; rsrc.close() + +def locking(path): + @With(closing(file(path, 'w'))) + def foo(f): + flock(f, LOCK_EX) + # here is where we fail! we'd need to yield two levels up the + # stack! + try: yield + finally: flock(f, LOCK_UN) + return foo + +# demos + +@With(closing(file('/tmp/hello', 'w'))) +def foo(f): print 'WRITING'; f.write('hello!') + +@With(locking('/tmp/mylock')) +def foo(): + print 'locked' + return raw_input() +print foo This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |