Parameters in context manager's __enter__ method?

Matimus mccredie at gmail.com
Wed Oct 24 23:40:24 CEST 2007


On Oct 24, 7:06 am, s... at 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:

[code]
fl = FileLock(...)
with FileLockContext(filelock=fl, timeout=1000):
   # do stuff
[/code]

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
[/code]

Or, you could go the same path you are already, using a hybrid, and
pass timeout to the FileLock constructor.

Matt




More information about the Python-list mailing list