Skip to content

Commit 2959d2c

Browse files
committed
Improve the bytes_to_native_str() family of functions in future.utils
This fixes issue #47
1 parent 3e6151a commit 2959d2c

File tree

1 file changed

+21
-14
lines changed

1 file changed

+21
-14
lines changed

future/utils/__init__.py

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -160,38 +160,45 @@ def tobytes(s):
160160
else:
161161
# Python 2
162162
def tobytes(s):
163-
'''
164-
Encodes to latin-1 (where the first 256 chars are the same as
165-
ASCII.)
166-
'''
167163
if isinstance(s, unicode):
168164
return s.encode('latin-1')
169165
else:
170166
return ''.join(s)
171167

168+
tobytes.__doc__ = """
169+
Encodes to latin-1 (where the first 256 chars are the same as
170+
ASCII.)
171+
"""
172+
172173
if PY3:
173-
def native_str_to_bytes(s, encoding='ascii'):
174+
def native_str_to_bytes(s, encoding='utf-8'):
174175
return s.encode(encoding)
175176

176-
def bytes_to_native_str(b, encoding='ascii'):
177+
def bytes_to_native_str(b, encoding='utf-8'):
177178
return b.decode(encoding)
178179

179-
def text_to_native_str(b, encoding='ascii'):
180-
return b
180+
def text_to_native_str(t, encoding=None):
181+
return t
181182
else:
182183
# Python 2
183-
def native_str_to_bytes(s, encoding='ascii'):
184-
return s
184+
def native_str_to_bytes(s, encoding=None):
185+
from future.types import newbytes # to avoid a circular import
186+
return newbytes(s)
185187

186-
def bytes_to_native_str(b, encoding='ascii'):
187-
return b
188+
def bytes_to_native_str(b, encoding=None):
189+
return native(b)
188190

189-
def text_to_native_str(b, encoding='ascii'):
191+
def text_to_native_str(t, encoding='ascii'):
190192
"""
191193
Use this to create a Py2 native string when "from __future__ import
192194
unicode_literals" is in effect.
193195
"""
194-
return b.encode(encoding)
196+
return unicode(t).encode(encoding)
197+
198+
native_str_to_bytes.__doc__ = """
199+
On Py3, returns an encoded string.
200+
On Py2, returns a newbytes type, ignoring the ``encoding`` argument.
201+
"""
195202

196203
if PY3:
197204
# list-producing versions of the major Python iterating functions

0 commit comments

Comments
 (0)