[ python-Bugs-1476356 ] StringIO should implement __str__()

SourceForge.net noreply at sourceforge.net
Wed Apr 26 04:53:28 CEST 2006


Bugs item #1476356, was opened at 2006-04-25 16:11
Message generated for change (Comment added) made by cinamod
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1476356&group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Python Library
Group: None
Status: Closed
Resolution: Invalid
Priority: 5
Submitted By: Dom Lachowicz (cinamod)
Assigned to: Nobody/Anonymous (nobody)
Summary: StringIO should implement __str__()

Initial Comment:
I was a bit surprised when I discovered that StringIO
didn't have a __str__() method, equivalent to
getvalue(). Calling str(stringio_object) gives the
following:

>>> import StringIO
>>> s = StringIO.StringIO("hello world")
>>> print "%s" % (str(s))
<StringIO.StringIO instance at 0x401ef08c>

I had some (perhaps dodgy code) code that did:

if isinstance(data, types.FileType):
  return data.read()
else:
  return str(data)

Since StringIO doesn't subclass any file type and
doesn't implement a __str__() method, I was getting
seemingly bogus results. This was trivially worked
around by adding another "isinstance(data,
StringIO.StringIO)" case, but it was surprising
nonetheless. Thanks.

----------------------------------------------------------------------

>Comment By: Dom Lachowicz (cinamod)
Date: 2006-04-25 22:53

Message:
Logged In: YES 
user_id=69417

The StringIO API diverges from the file API already. It adds
API (getvalue()) doesn't implement the encoding, mode, name,
newlines, or softspace attributes, and implements isatty()
in violation of the section 2.3.9 docs.

In some contexts, it may look like a file, but it isn't a
file. And I don't see how implementing __str__() changes
that. It's equivalent to saying that Java's StringBuffer
class shouldn't override toString()...

----------------------------------------------------------------------

Comment By: Raymond Hettinger (rhettinger)
Date: 2006-04-25 18:58

Message:
Logged In: YES 
user_id=80475

This isn't a bug.  The module is correctly emulating the API
for file objects.

I recommend replacing your isintance() test with a try/except:

try:
.... return data.read()
except AttributeError:
.... return str(data)



----------------------------------------------------------------------

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1476356&group_id=5470


More information about the Python-bugs-list mailing list