@@ -6,6 +6,7 @@ Conversion functions for bytes/unicode
6
6
import sys
7
7
encoding = sys.getfilesystemencoding()
8
8
9
+
9
10
cpdef bytes to_bytes(s):
10
11
"""
11
12
Converts bytes and unicode ``s`` to bytes.
@@ -16,17 +17,26 @@ cpdef bytes to_bytes(s):
16
17
>>> s1 = to_bytes(b'hello')
17
18
>>> s2 = to_bytes('hello')
18
19
>>> s3 = to_bytes(u'hello')
19
- >>> type(s1) == type(s2) == type(s3) == bytes
20
+ >>> type(s1) is type(s2) is type(s3) is bytes
20
21
True
21
22
>>> s1 == s2 == s3 == b'hello'
22
23
True
24
+
25
+ >>> type(to_bytes(1234)) is bytes
26
+ True
27
+ >>> int(to_bytes(1234))
28
+ 1234
23
29
"""
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
+
30
40
31
41
cpdef unicode to_unicode(s):
32
42
r """
@@ -38,17 +48,18 @@ cpdef unicode to_unicode(s):
38
48
>>> s1 = to_unicode( b'hello')
39
49
>>> s2 = to_unicode( 'hello')
40
50
>>> 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"")
44
52
True
45
53
>>> s1 == s2 == s3 == u'hello'
46
54
True
55
+
56
+ >>> print( to_unicode( 1234))
57
+ 1234
58
+ >>> type( to_unicode( 1234)) is type( u"")
59
+ True
47
60
"""
48
61
if isinstance (s, bytes):
49
62
return (< bytes> s).decode(encoding)
50
63
elif isinstance (s, unicode ):
51
64
return < unicode > s
52
- else :
53
- raise TypeError
54
-
65
+ return unicode (s)
0 commit comments