equal
deleted
inserted
replaced
85 >>> bytestr(), bytestr(bytearray(b'foo')), bytestr(u'ascii'), bytestr(1) |
85 >>> bytestr(), bytestr(bytearray(b'foo')), bytestr(u'ascii'), bytestr(1) |
86 (b'', b'foo', b'ascii', b'1') |
86 (b'', b'foo', b'ascii', b'1') |
87 >>> s = bytestr(b'foo') |
87 >>> s = bytestr(b'foo') |
88 >>> assert s is bytestr(s) |
88 >>> assert s is bytestr(s) |
89 |
89 |
|
90 __bytes__() should be called if provided: |
|
91 |
|
92 >>> class bytesable(object): |
|
93 ... def __bytes__(self): |
|
94 ... return b'bytes' |
|
95 >>> bytestr(bytesable()) |
|
96 b'bytes' |
|
97 |
90 There's no implicit conversion from non-ascii str as its encoding is |
98 There's no implicit conversion from non-ascii str as its encoding is |
91 unknown: |
99 unknown: |
92 |
100 |
93 >>> bytestr(chr(0x80)) # doctest: +ELLIPSIS |
101 >>> bytestr(chr(0x80)) # doctest: +ELLIPSIS |
94 Traceback (most recent call last): |
102 Traceback (most recent call last): |
125 """ |
133 """ |
126 |
134 |
127 def __new__(cls, s=b''): |
135 def __new__(cls, s=b''): |
128 if isinstance(s, bytestr): |
136 if isinstance(s, bytestr): |
129 return s |
137 return s |
130 if not isinstance(s, (bytes, bytearray)): |
138 if (not isinstance(s, (bytes, bytearray)) |
|
139 and not hasattr(s, u'__bytes__')): # hasattr-py3-only |
131 s = str(s).encode(u'ascii') |
140 s = str(s).encode(u'ascii') |
132 return bytes.__new__(cls, s) |
141 return bytes.__new__(cls, s) |
133 |
142 |
134 def __getitem__(self, key): |
143 def __getitem__(self, key): |
135 s = bytes.__getitem__(self, key) |
144 s = bytes.__getitem__(self, key) |