Using the 'with' statement with cStringIO objects

P

peppergrower

I've been experimenting with the 'with' statement (in __future__), and
so far I like it. However, I can't get it to work with a cStringIO
object. Here's a minimum working example:

###
from __future__ import with_statement
import cStringIO

teststring='this is a test'

with cStringIO.StringIO(teststring) as testfile:
pass
###

I get the following error message:

Traceback (most recent call last):
File "testfile.py", line 6, in <module>
with cStringIO.StringIO(teststring) as testfile:
AttributeError: 'cStringIO.StringI' object has no attribute '__exit__'

So, I'm guessing you can't use the 'with' statement with cStringIO
objects? Is this a bug, or do I need to use the 'with' statement
differently to get this to work?

Thanks,
peppergrower
 
F

Fredrik Lundh

peppergrower said:
teststring='this is a test'

with cStringIO.StringIO(teststring) as testfile:
pass

umm. what exactly do you expect that code to do?

</F>
 
P

peppergrower

Thanks for the help. I'm fairly new to programming (which you
probably could have guessed...). When I realized that you could use a
StringIO instance as if it were a file, I wanted to try some of the
same techniques on it as I would with a file. In this case, I wanted
to use a "for line in testfile" construction to iterate over the
StringIO instance. (I did find a better way for my particular case,
one that didn't involve StringIO at all.) When I got that particular
error, I suspected that it had something to do with the relative
newness of the 'with' statement.

If this is something that should be considered for addition in the
future, is there somewhere specific I should suggest that?
 
G

Gabriel Genellina

En Sat, 27 Sep 2008 19:28:49 -0300, peppergrower
When I got that particular
error, I suspected that it had something to do with the relative
newness of the 'with' statement.

If this is something that should be considered for addition in the
future, is there somewhere specific I should suggest that?

Yes: http://bugs.python.org/ (setting type="feature request", I think)
 

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
474,432
Messages
2,571,681
Members
48,796
Latest member
Greg L.

Latest Threads

Top