First, as a strategy, I would take a small part of your program and try to port it. The number of unicode
calls you are describing suggest to me that your application cares about string representations more than most and each use-case is often different.
The important consideration is that all strings are unicode in Python 3. If you are using the str
type to store "bytes" (for example, if they are read from a file), then you should be aware that those will not be bytes in Python3 but will be unicode characters to begin with.
Let's look at a few cases.
First, if you do not have any non-ASCII characters at all and really are not using the Unicode character set, it is easy. Chances are you can simply change the unicode()
function to str()
. That will assure that any object passed as an argument is properly converted. However, it is wishful thinking to assume it's that easy.
Most likely, you'll need to look at the argument to unicode()
to see what it is, and determine how to treat it.
For example, if you are reading UTF-8 characters from a file in Python 2 and converting them to Unicode your code would look like this:
data = open('somefile', 'r').read()
udata = unicode(data)
However, in Python3, read()
returns Unicode data to begin with, and the unicode decoding must be specified when opening the file:
udata = open('somefile', 'r', encoding='UTF-8').read()
As you can see, transforming unicode()
simply when porting may depend heavily on how and why the application is doing Unicode conversions, where the data has come from, and where it is going to.
Python3 brings greater clarity to string representations, which is welcome, but can make porting daunting. For example, Python3 has a proper bytes
type, and you convert byte-data to unicode like this:
udata = bytedata.decode('UTF-8')
or convert Unicode data to character form using the opposite transform.
bytedata = udata.encode('UTF-8')
I hope this at least helps determine a strategy.
unicode()
calls. I the code base which I currently work on, there are about 700 calls to this method. What should I do? – guettli Aug 1 '16 at 13:57unicode
and you're good to go. All strings are unicode in Python 3. If this does not work, then expect lots of work. The transition from str to unicode literals and bytes is by far the most incompatible change when switching from Python 2 to 3. – Phillip Aug 3 '16 at 15:07unicode()
function that does nothing butreturn str(arg)
in Python 3? – martineau Aug 3 '16 at 16:40str
tounicode
-unicode = str
(without parenthesis). It should work. – furas Aug 3 '16 at 16:57