Using the 'with' statement with cStringIO objects

Hrvoje Niksic hniksic at
Sat Sep 27 17:16:01 CEST 2008

George Boutsioukis <gboutsioukis at> writes:

> Neither, just not implemented. Only classes with __enter__ and
> __exit__ methods(ie context manager types) can be used in with
> statements. And, correct me if I'm wrong, I think it's pointless for
> a StringIO object to have those.

It's definitely superfluous, but it should still be provided, for the
same reason a "close" method is provided, to allow StringIO objects to
be treated like other file-like objects.  For example, code that does
the following:

with obj.open_file(...) as f:

shouldn't have to care if obj.open_file returns a built-in file
instance, or a StringIO instance.  As the above code becomes more
popular, __enter__ and __exit__ are beginning to be part of the file
interface (in the duck-typing sense) and should be implemented.

Until then, the the contextlib.closing context manager can be used

with contextlib.closing(obj.open_file(...)) as f:

More information about the Python-list mailing list