On Oct 24, 7:06 am, s...@pobox.com wrote:
I am working on a file locking class which I'd like to work with Python
2.5's context managers. The acquire method takes an optional timeout
argument:
class FileLock:
...
def acquire(self, timeout=None):
...
def __enter__(self):
self.acquire()
return self
Can that optional timeout be somehow accommodated by the with statement?
(I'm thinking no, which may not be a big shortcoming anyway.)
Thx,
Skip
I think a better solution might be to create a locking class, and a
seperate context manager class. That way you can pass the timeout as a
parameter to the context managers constructor:
-
fl = FileLock(...)
-
with FileLockContext(filelock=fl, timeout=1000):
-
# do stuff
-
But another option along the same line might be to have the acquire
method return the context instance. Then you could write:
-
class FileLockContext(fl, timeout):
-
...
-
-
class FileLock:
-
...
-
def acquire(self, timeout=None):
-
# do acquiring
-
return FileLockContext(self, timeout)
-
-
fl = FileLock(...)
-
with fl.acquire(1000):
-
#do stuff
-
Or, you could go the same path you are already, using a hybrid, and
pass timeout to the FileLock constructor.
Matt