Skip to content

Instantly share code, notes, and snippets.

@prologic
Created August 25, 2015 01:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prologic/24cafc7315596b8683ca to your computer and use it in GitHub Desktop.
Save prologic/24cafc7315596b8683ca to your computer and use it in GitHub Desktop.
Supporting Python 2/3 and Unicode

Python 2/3 Unicode

Basic Rules

  • Use six
  • Use six.u() everywhere you expose a Unicode/String API (anything that is meant for Humans!)
  • Use six.text_type() in place of unicode()
  • Implement the following "Python special methods":
import sys


# True if we are running on Python 3.
PY3 = sys.version_info[0] == 3


from six import text_typu


class Thing(object)

    def __init__(self, name, encodig="utf-8"):
        self.name = name
        self.encoding = encoding
        
    def __str__(self):
        return self.__unicode__() if PY3 else self.__bytes__()

    def __bytes__(self):
        return text_type(self).encode(self.encoding)

    def __unicode__(self):
        return u("{0}".format(self.name))

    def __repr__(self):
        return repr(text_type(self))
@spaceone
Copy link

s/text_typu/text_type/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment