Parameters in context manager's __enter__ method?

S

skip

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
 
M

Matimus

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:

Code:
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:

Code:
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
 

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

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top