Skip to content

Commit 905e526

Browse files
committed
to_bytes and to_unicode: convert if needed
1 parent acefe82 commit 905e526

File tree

1 file changed

+24
-13
lines changed

1 file changed

+24
-13
lines changed

cypari2/string_utils.pyx

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ Conversion functions for bytes/unicode
66
import sys
77
encoding = sys.getfilesystemencoding()
88

9+
910
cpdef bytes to_bytes(s):
1011
"""
1112
Converts bytes and unicode ``s`` to bytes.
@@ -16,17 +17,26 @@ cpdef bytes to_bytes(s):
1617
>>> s1 = to_bytes(b'hello')
1718
>>> s2 = to_bytes('hello')
1819
>>> s3 = to_bytes(u'hello')
19-
>>> type(s1) == type(s2) == type(s3) == bytes
20+
>>> type(s1) is type(s2) is type(s3) is bytes
2021
True
2122
>>> s1 == s2 == s3 == b'hello'
2223
True
24+
25+
>>> type(to_bytes(1234)) is bytes
26+
True
27+
>>> int(to_bytes(1234))
28+
1234
2329
"""
24-
if isinstance(s, bytes):
25-
return <bytes> s
26-
elif isinstance(s, unicode):
27-
return (<unicode> s).encode(encoding)
28-
else:
29-
raise TypeError
30+
cdef int convert
31+
for convert in range(2):
32+
if convert:
33+
s = str(s)
34+
if isinstance(s, bytes):
35+
return <bytes> s
36+
elif isinstance(s, unicode):
37+
return (<unicode> s).encode(encoding)
38+
raise AssertionError(f"str() returned {type(s)}")
39+
3040

3141
cpdef unicode to_unicode(s):
3242
r"""
@@ -38,17 +48,18 @@ cpdef unicode to_unicode(s):
3848
>>> s1 = to_unicode(b'hello')
3949
>>> s2 = to_unicode('hello')
4050
>>> s3 = to_unicode(u'hello')
41-
>>> import sys
42-
>>> u_type = (unicode if sys.version_info.major <= 2 else str)
43-
>>> type(s1) == type(s2) == type(s3) == u_type
51+
>>> type(s1) is type(s2) is type(s3) is type(u"")
4452
True
4553
>>> s1 == s2 == s3 == u'hello'
4654
True
55+
56+
>>> print(to_unicode(1234))
57+
1234
58+
>>> type(to_unicode(1234)) is type(u"")
59+
True
4760
"""
4861
if isinstance(s, bytes):
4962
return (<bytes> s).decode(encoding)
5063
elif isinstance(s, unicode):
5164
return <unicode> s
52-
else:
53-
raise TypeError
54-
65+
return unicode(s)

0 commit comments

Comments
 (0)