Public
Anyone know how to make this bit of code work in both Python 2.x and Python 3.x? In python2, path appears to always be a unicode object, and in python3, it is a str.
def unicode_path_thing(key):
path = os.environ.get(key)
return path.decode(sys.getfilesystemencoding()).encode("utf-8")
def unicode_path_thing(key):
path = os.environ.get(key)
return path.decode(sys.getfilesystemencoding()).encode("utf-8")
View 15 previous comments
Mind you, I'm on my second beer.Jun 23, 2012
wait. You encode at the end. That means by definition you get a string in 2 and bytes in 3, if your test assumes a string, then it's never gonna work in python 3 since there you have no strings, only bytes or unicode. Just test isinstance(bytes, path) and if so, compare to b'whatever'Jun 23, 2012
That is assuming bytes is an actual type, but I would think so.Jun 23, 2012
The encode() at the end is gone now. I'm using os.environb.get in Python 3, and os.environ.get in Python 2. So it's just doing the return path.decode(sys.getfilesystemencoding()) now.Jun 23, 2012
Also, it's either unicode or bytes in both versions, since I'm importing unicode_literals as well.Jun 23, 2012
+Jason DeRose , str.encode(x) silently performs str.decode(defaultencoding).encode(x) . unicode.decode also has a silent .encode(defaultencoding) in it too. It's evil.Jun 23, 2012