471,350 Members | 1,723 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

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

Need some help with 'with'

I recently found myself needing to do this a lot:

lock a record in a file
read the record into a buffer
alter the buffer
write the buffer back to the record
unlock the record

I'd love to be able to create a context for this to use with the
'with' statement, something like:

from __future__ import with_statement
from contextlib import contextmanager
from fcntl import lockf, LOCK_EX, LOCK_UN

@contextmanager
def lockedRecord(fileObj, offset, length):
lockf(fileObj, LOCK_EX, offset, length)
try:
fileObj.seek(offset)
buff = fileObj.read(length)
newBuff = (yield buff)
fileObj.seek(offset)
fileObj.write(newBuff)
finally:
lockf(fileObj, LOCK_UN, offset, length)

Which would let me write code like:

fileObj = open("myfile.dat", "r+b")

with lockedRecord(fileObj, 20, 10) as rec:
newRec = rec.replace('foo', 'bar')
# Somehow send newRec back into the context

I know you can now send data back into a generator via the send method
of the generator, however i don't seem to have access to the generator
object itself.

I figure that if instead of returning the buffer from the context
directly, I instead returned the buffer in a list, I could then change
the buffer, put it in the returned list, then I'd have access to it
back inside the context, but this seems a bit ugly.

Does anyone have insight into the right way of doing this?
Nov 28 '07 #1
1 881
In article <d7**********************************@w40g2000hsb. googlegroups.com>,
Mike Kent <mr******@cox.netwrote:
>
I figure that if instead of returning the buffer from the context
directly, I instead returned the buffer in a list, I could then change
the buffer, put it in the returned list, then I'd have access to it
back inside the context, but this seems a bit ugly.

Does anyone have insight into the right way of doing this?
You're almost at the right approach: just create a class instance that
contains a buffer attribute.
--
Aahz (aa**@pythoncraft.com) <* http://www.pythoncraft.com/

"Typing is cheap. Thinking is expensive." --Roy Smith
Nov 30 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

6 posts views Thread by mike | last post: by
7 posts views Thread by Timothy Shih | last post: by
2 posts views Thread by bryan | last post: by
8 posts views Thread by skumar434 | last post: by
reply views Thread by U S Contractors Offering Service A Non-profit | last post: by
reply views Thread by XIAOLAOHU | 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.