NameError: global name 'unicode' is not defined - in Python 3 NameError: global name 'unicode' is not defined - in Python 3 python python

NameError: global name 'unicode' is not defined - in Python 3


Python 3 renamed the unicode type to str, the old str type has been replaced by bytes.

if isinstance(unicode_or_str, str):    text = unicode_or_str    decoded = Falseelse:    text = unicode_or_str.decode(encoding)    decoded = True

You may want to read the Python 3 porting HOWTO for more such details. There is also Lennart Regebro's Porting to Python 3: An in-depth guide, free online.

Last but not least, you could just try to use the 2to3 tool to see how that translates the code for you.


If you need to have the script keep working on python2 and 3 as I did, this might help someone

import sysif sys.version_info[0] >= 3:    unicode = str

and can then just do for example

foo = unicode.lower(foo)


You can use the six library to support both Python 2 and 3:

import sixif isinstance(value, six.string_types):    handle_string(value)