import unittest
from fcntl import flock, LOCK_EX, LOCK_UN
-from os import remove
class struct(object):
'A simple namespace object.'
#
def with_closing(rsrc):
- "Utility to emulate Python 2.5's `with closing(rsrc)` context manager."
+ """
+ Utility to emulate Python 2.5's `with closing(rsrc)` context manager.
+
+ E.g.,
+ @with_closing(file('/tmp/foo'))
+ def contents(f):
+ return f.read()
+ # now 'contents' is the contents of /tmp/foo
+ """
def wrapper(func):
try: return func(rsrc)
finally: rsrc.close()
def input():
print 'locked'
return raw_input()
- # decorator is executed immediately
- print input # prints the input text
+ # prints 'locked'
+ print input # prints what raw_input() returned
"""
def wrapper(func):
@with_closing(file(path, 'w'))
flock(f, LOCK_EX)
try: return func()
finally: flock(f, LOCK_UN)
- remove(path)
return g
return wrapper