@@ -46,11 +46,21 @@ def asUnicode(s):
4646 except :
4747 return str (s )
4848
49- def ensureUtf (s ):
50- if type (s ) == unicode :
51- return s .encode ('utf8' , 'ignore' )
49+ def toUnicode (s , encoding = 'utf8' ):
50+ """Converts input to unicode if necessary.
51+
52+ If `s` is bytes, it will be decoded using the `encoding` parameters.
53+
54+ This function is used for preprocessing /source/ and /filename/ arguments
55+ to the builtin function `compile`.
56+ """
57+ # In Python2, str == bytes.
58+ # In Python3, bytes remains unchanged, but str means unicode
59+ # while unicode is not defined anymore
60+ if type (s ) == bytes :
61+ return s .decode (encoding , 'ignore' )
5262 else :
53- return str ( s )
63+ return s
5464
5565def findLoc (body , line , total ):
5666 for i in range (len (body )):
@@ -190,11 +200,11 @@ def handleEval(data):
190200 loc = form [0 ]
191201 isEval = False
192202 try :
193- code = compile (ensureUtf (code ), ensureUtf (data [2 ]["name" ]), 'eval' )
203+ code = compile (toUnicode (code ), toUnicode (data [2 ]["name" ]), 'eval' )
194204 isEval = True
195205 except :
196206 try :
197- code = compile (ensureUtf (code ), ensureUtf (data [2 ]["name" ]), 'exec' )
207+ code = compile (toUnicode (code ), toUnicode (data [2 ]["name" ]), 'exec' )
198208 except :
199209 e = traceback .format_exc ()
200210 send (data [0 ], "editor.eval.python.exception" , {"ex" : cleanTrace (e ), "meta" : loc })
@@ -260,11 +270,11 @@ def ipyEval(data):
260270 loc = form [0 ]
261271 isEval = False
262272 try :
263- compile (ensureUtf (code ), ensureUtf (data [2 ]["name" ]), 'eval' )
273+ compile (toUnicode (code ), toUnicode (data [2 ]["name" ]), 'eval' )
264274 isEval = True
265275 except :
266276 try :
267- compile (ensureUtf (code ), ensureUtf (data [2 ]["name" ]), 'exec' )
277+ compile (toUnicode (code ), toUnicode (data [2 ]["name" ]), 'exec' )
268278 except :
269279 e = traceback .format_exc ()
270280 send (data [0 ], "editor.eval.python.exception" , {"ex" : cleanTrace (e ), "meta" : loc })
0 commit comments