Skip to content

Commit 4009115

Browse files
committed
Added a to_unicode() utility method
Also added a UNICODE_TYPE constant
1 parent d4de9a0 commit 4009115

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

javaobj/utils.py

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def log_debug(message, ident=0):
5656
:param message: Message to log
5757
:param ident: Number of indentation spaces
5858
"""
59-
_log.debug("%s%s", " " * (ident * 2), message)
59+
_log.debug("%s%s", " " * (ident * 2), message)
6060

6161

6262
def log_error(message, ident=0):
@@ -66,12 +66,14 @@ def log_error(message, ident=0):
6666
:param message: Message to log
6767
:param ident: Number of indentation spaces
6868
"""
69-
_log.error("%s%s", " " * (ident * 2), message)
69+
_log.error("%s%s", " " * (ident * 2), message)
7070

7171

7272
# ------------------------------------------------------------------------------
7373

7474
if sys.version_info[0] >= 3:
75+
UNICODE_TYPE = str
76+
7577
# Python 3 interpreter : bytes & str
7678
def to_bytes(data, encoding="UTF-8"):
7779
"""
@@ -104,6 +106,9 @@ def to_str(data, encoding="UTF-8"):
104106
except UnicodeDecodeError:
105107
return decode_modified_utf8(data)[0]
106108

109+
# Same operation
110+
to_unicode = to_str
111+
107112
def read_to_str(data):
108113
"""
109114
Concats all bytes into a string
@@ -112,6 +117,8 @@ def read_to_str(data):
112117

113118

114119
else:
120+
UNICODE_TYPE = unicode
121+
115122
# Python 2 interpreter : str & unicode
116123
def to_str(data, encoding="UTF-8"):
117124
"""
@@ -130,6 +137,24 @@ def to_str(data, encoding="UTF-8"):
130137
# Same operation
131138
to_bytes = to_str
132139

140+
# Python 2 interpreter : str & unicode
141+
def to_unicode(data, encoding="UTF-8"):
142+
"""
143+
Converts the given parameter to a string.
144+
Returns the first parameter if it is already an instance of ``str``.
145+
146+
:param data: A string
147+
:param encoding: The encoding of data
148+
:return: The corresponding string
149+
"""
150+
if type(data) is unicode:
151+
# Nothing to do
152+
return data
153+
try:
154+
return data.decode(encoding)
155+
except UnicodeDecodeError:
156+
return decode_modified_utf8(data)[0]
157+
133158
def read_to_str(data):
134159
"""
135160
Nothing to do in Python 2

0 commit comments

Comments
 (0)