Skip to content
Advertisement

how to convert Python 2 unicode() function into correct Python 3.x syntax

I enabled the compatibility check in my Python IDE and now I realize that the inherited Python 2.7 code has a lot of calls to unicode() which are not allowed in Python 3.x.

I looked at the docs of Python2 and found no hint how to upgrade:

I don’t want to switch to Python3 now, but maybe in the future.

The code contains about 500 calls to unicode()

How to proceed?

Update

The comment of user vaultah to read the pyporting guide has received several upvotes.

My current solution is this (thanks to Peter Brittain):

from builtins import str

… I could not find this hint in the pyporting docs…..

Advertisement

Answer

As has already been pointed out in the comments, there is already advice on porting from 2 to 3.

Having recently had to port some of my own code from 2 to 3 and maintain compatibility for each for now, I wholeheartedly recommend using python-future, which provides a great tool to help update your code (futurize) as well as clear guidance for how to write cross-compatible code.

In your specific case, I would simply convert all calls to unicode to use str and then import str from builtins. Any IDE worth its salt these days will do that global search and replace in one operation.

Of course, that’s the sort of thing futurize should catch too, if you just want to use automatic conversion (and to look for other potential issues in your code).

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement