pycompat: try __bytes__() to convert object to bytestr
authorYuya Nishihara <yuya@tcha.org>
Thu, 04 May 2017 11:51:07 +0900
changeset 32450 548478efc46c
parent 32449 0ed730f3301c
child 32451 bce5ebe72859
pycompat: try __bytes__() to convert object to bytestr It should be better than using __str__() unconditionally.
mercurial/pycompat.py
--- a/mercurial/pycompat.py	Tue May 23 15:44:50 2017 +0200
+++ b/mercurial/pycompat.py	Thu May 04 11:51:07 2017 +0900
@@ -87,6 +87,14 @@
         >>> s = bytestr(b'foo')
         >>> assert s is bytestr(s)
 
+        __bytes__() should be called if provided:
+
+        >>> class bytesable(object):
+        ...     def __bytes__(self):
+        ...         return b'bytes'
+        >>> bytestr(bytesable())
+        b'bytes'
+
         There's no implicit conversion from non-ascii str as its encoding is
         unknown:
 
@@ -127,7 +135,8 @@
         def __new__(cls, s=b''):
             if isinstance(s, bytestr):
                 return s
-            if not isinstance(s, (bytes, bytearray)):
+            if (not isinstance(s, (bytes, bytearray))
+                and not hasattr(s, u'__bytes__')):  # hasattr-py3-only
                 s = str(s).encode(u'ascii')
             return bytes.__new__(cls, s)