Skip to content

Instantly share code, notes, and snippets.

@sampsyo
Created June 30, 2016 05:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sampsyo/9a9236cb255b3ff3d9049979df80ee9d to your computer and use it in GitHub Desktop.
Save sampsyo/9a9236cb255b3ff3d9049979df80ee9d to your computer and use it in GitHub Desktop.
import sys
import os
PY2 = sys.version_info[0] == 2
def py3_path(path):
"""Convert a bytestring path to Unicode on Python 3 only. On Python
2, return the bytestring path unchanged.
This helps deal with APIs on Python 3 that *only* accept Unicode
(i.e., `str` objects). I philosophically disagree with this
decision, because paths are sadly bytes on Unix, but that's the way
it is. So this function helps us "smuggle" the true bytes data
through APIs that took Python 3's Unicode mandate too seriously.
"""
assert isinstance(path, bytes)
if PY2:
return path
return os.fsdecode(path)
if __name__ == '__main__':
os.environ['something'] = py3_path(u'caf\xe9'.encode('utf8'))
print(os.environ['something'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment