471,330 Members | 1,588 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,330 software developers and data experts.

Parameters in context manager's __enter__ method?


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
Oct 24 '07 #1
1 3607
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:

Expand|Select|Wrap|Line Numbers
  1. fl = FileLock(...)
  2. with FileLockContext(filelock=fl, timeout=1000):
  3. # do stuff
  4.  
But another option along the same line might be to have the acquire
method return the context instance. Then you could write:

Expand|Select|Wrap|Line Numbers
  1. class FileLockContext(fl, timeout):
  2. ...
  3.  
  4. class FileLock:
  5. ...
  6. def acquire(self, timeout=None):
  7. # do acquiring
  8. return FileLockContext(self, timeout)
  9.  
  10. fl = FileLock(...)
  11. with fl.acquire(1000):
  12. #do stuff
  13.  
Or, you could go the same path you are already, using a hybrid, and
pass timeout to the FileLock constructor.

Matt

Oct 24 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by SPG | last post: by
11 posts views Thread by Andrew Thompson | last post: by
2 posts views Thread by freddy | last post: by
reply views Thread by Mikolai Fajer | last post: by
reply views Thread by Gabriel Genellina | last post: by
reply views Thread by rosydwin | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.