Let's assume you have the following Python2 Code:
#!/usr/bin/env python
import struct
struct.pack('s', 'hello')
This works fine under Python2, but it won't run under Python3, as the implementation of struct.pack changed. struct.pack now expects a bytes object for a string identifier and not a string any more. The fix for running this code under Python3 would be something like:
struct.pack('s', bytes('hello', 'utf-8')). But again, this code will not run under Python2 :-)
I'm trying to code version independent as I don't want to force anybody to install python2 or 3.
What would be the best approach for getting this piece of code version independent?
1 Answer 1
The Python 2 str type was basically renamed to bytes in Python 3, while the unicode type became str. You are in essence sending bytestrings in Python 2 and Unicode strings in Python 3 to struct.pack().
It could be the correct fix is to use Unicode everywhere in both Python 2 and 3 (and thus always encode when using struct.pack(), regardless of the Python version).
The alternative is to use an isinstance test:
value = 'hello'
if not isinstance(value, bytes):
vaule = value.encode('utf8')
This works in both Python 2 and 3, because in Python 2 bytes is an alias for str.
stris a bytestring. It is notstructthat changed, it is the Python string object. Python 2unicodebecamestrin Python 3, Python 2strbecamebytesin Python 3.b'hello'will work in both Python 2 and 3 if you are using literals.strtype is the same thing asunicodein Python 2. You'd encodeunicodevalues in Python 2 too.