lennyfoulds
lennyfoulds

Reputation: 38

Best way to port over Python 2.7 byte strings to Python 3

I am currently porting Python 2.7 code over to Python 3 and I am having trouble determining what the best approach to handle strings.

I have Python scripts which have the following imports:

from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from __future__ import unicode_literals

Now since the unicode_literals converts all of my strings in Python 2.7 scripts, I get errors like this in my script:

TypeError: expecting a string or number, unicode found
TypeError: Argument 'key' has incorrect type (expected str, got unicode)

Now I can get rid of the errors in Python2.7 by simply adding .encode('utf-8') to every string. For example:

scanline_node['projection_mode'].setValue("uv")
TypeError: expecting a string or number, unicode found
scanline_node['projection_mode'].setValue("uv".encode('utf-8'))

My problem is that when I start using Python 3, that won't work because it will make the type of string to bytes.

My question is, what is the best way to handle this type of issue so that my code will work on Python 2.7 and Python 3? Should I just use the builtin str()?

Thanks!

Jared

Upvotes: 0

Views: 305

Answers (1)

uanirudhx
uanirudhx

Reputation: 316

You should be using the six library. It helps code work on both Python 2 & 3. Six contains a type called six.text_type which is unicode on Python 2, and str on Python 3. You can then use that as the type your function expects.

Upvotes: 1

Related Questions