Commit 2a16eea7 authored by Daniel Fortunov's avatar Daniel Fortunov Committed by Raymond Hettinger

bpo-36582: Make collections.UserString.encode() return bytes, not str (GH-13138)

parent 98d90f74
...@@ -1184,12 +1184,10 @@ class UserString(_collections_abc.Sequence): ...@@ -1184,12 +1184,10 @@ class UserString(_collections_abc.Sequence):
if isinstance(sub, UserString): if isinstance(sub, UserString):
sub = sub.data sub = sub.data
return self.data.count(sub, start, end) return self.data.count(sub, start, end)
def encode(self, encoding=None, errors=None): # XXX improve this? def encode(self, encoding='utf-8', errors='strict'):
if encoding: encoding = 'utf-8' if encoding is None else encoding
if errors: errors = 'strict' if errors is None else errors
return self.__class__(self.data.encode(encoding, errors)) return self.data.encode(encoding, errors)
return self.__class__(self.data.encode(encoding))
return self.__class__(self.data.encode())
def endswith(self, suffix, start=0, end=_sys.maxsize): def endswith(self, suffix, start=0, end=_sys.maxsize):
return self.data.endswith(suffix, start, end) return self.data.endswith(suffix, start, end)
def expandtabs(self, tabsize=8): def expandtabs(self, tabsize=8):
......
...@@ -51,6 +51,20 @@ class UserStringTest( ...@@ -51,6 +51,20 @@ class UserStringTest(
str3 = ustr3('TEST') str3 = ustr3('TEST')
self.assertEqual(fmt2 % str3, 'value is TEST') self.assertEqual(fmt2 % str3, 'value is TEST')
def test_encode_default_args(self):
self.checkequal(b'hello', 'hello', 'encode')
# Check that encoding defaults to utf-8
self.checkequal(b'\xf0\xa3\x91\x96', '\U00023456', 'encode')
# Check that errors defaults to 'strict'
self.checkraises(UnicodeError, '\ud800', 'encode')
def test_encode_explicit_none_args(self):
self.checkequal(b'hello', 'hello', 'encode', None, None)
# Check that encoding defaults to utf-8
self.checkequal(b'\xf0\xa3\x91\x96', '\U00023456', 'encode', None, None)
# Check that errors defaults to 'strict'
self.checkraises(UnicodeError, '\ud800', 'encode', None, None)
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
...@@ -512,6 +512,7 @@ Arnaud Fontaine ...@@ -512,6 +512,7 @@ Arnaud Fontaine
Michael Foord Michael Foord
Amaury Forgeot d'Arc Amaury Forgeot d'Arc
Doug Fort Doug Fort
Daniel Fortunov
Evens Fortuné Evens Fortuné
Chris Foster Chris Foster
John Fouhy John Fouhy
......
Fix ``UserString.encode()`` to correctly return ``bytes`` rather than a ``UserString`` instance.
\ No newline at end of file
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment