Skip to content

Instantly share code, notes, and snippets.

@moreati
Last active January 20, 2026 16:52
Show Gist options
  • Select an option

  • Save moreati/6e0239e9057e8fda147ce12321011e5d to your computer and use it in GitHub Desktop.

Select an option

Save moreati/6e0239e9057e8fda147ce12321011e5d to your computer and use it in GitHub Desktop.
Testing behaviours of io.BytesIO, io StringIO, cStringIO.StringIO, and StringIO.StringIO
# coding: utf-8
from __future__ import print_function
import re
import sys
ARGUMENTS = [
(u'()', ()),
(u"(b'abc')", (b'abc',)),
(u"(u'abc')", (u'abc',)),
(u"(u'αβγ')", (u'αβγ',)),
]
CONSTRUCTORS = []
if sys.version_info >= (2, 6):
import io
CONSTRUCTORS += [
(u'io.BytesIO', io.BytesIO),
(u'io.StringIO', io.StringIO),
]
if sys.version_info >= (3, 0):
def repr_(s):
if isinstance(s, str):
return 'u%r' % (s,)
return repr(s)
else:
import cStringIO
import StringIO
CONSTRUCTORS += [
(u'cStringIO.StringIO', cStringIO.StringIO),
(u'StringIO.StringIO', StringIO.StringIO),
]
def repr_(s):
if isinstance(s, bytes):
return u'b%r' % (s,)
if isinstance(s, unicode):
return u"u'%s'" % (s,)
return repr(s).decode('ascii')
PY = u'py%d.%d' % sys.version_info[:2]
print(u'{: <6} {: <26} {: <33}'.format(u'Python', u'Constructor', u'Result'))
print(u'{:-<6} {:-<26} {:-<33}'.format(u'', u'', u''))
for ctor_name, ctor in CONSTRUCTORS:
for args_repr, args in ARGUMENTS:
ctor_repr = u'%s%s' % (ctor_name, args_repr)
try:
result = ctor(*args)
except Exception as exc:
result = exc
result_repr = type(exc).__name__
else:
result_repr = re.sub(r'at 0x[0-9a-f]+', '...', repr(result))
print(u'{: <6} {: <26} {: <33}'.format(PY, ctor_repr, result_repr))
del result
if sys.version_info < (3, 0):
print()
print(u'{: <6} {: <67} {: <10}'.format(u'Python', u'Constructor', u'Result'))
print(u'{:-<6} {:-<67} {:-<10}'.format(u'', u'', u''))
for templ in [
'%sStringIO.StringIO().getvalue()',
"%sStringIO.StringIO(b'a').getvalue()",
"%sStringIO.StringIO(u'a').getvalue()",
r"s = StringIO.StringIO(u'\u03b1\u03b2\u03b3'); %ss.getvalue()",
"s = StringIO.StringIO(); s.write(b'a'); %ss.getvalue()",
"s = StringIO.StringIO(); s.write(u'a'); %ss.getvalue()",
"s = StringIO.StringIO(); s.write(b'a'); s.write(u'a'); %ss.getvalue()",
"s = StringIO.StringIO(); s.write(u'a'); s.write(b'a'); %ss.getvalue()",
]:
label = templ % ''
code = templ % 'result = '
exec (code)
print(u'{: <6} {: <67} {: <10}'.format(PY, label, repr_(result)))
@moreati
Copy link
Author

moreati commented Jan 20, 2026

@moreati
Copy link
Author

moreati commented Jan 20, 2026

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment