Skip to content

Instantly share code, notes, and snippets.

Created December 13, 2013 21:28
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Python 3.3 compatible magic string methods
import six
class FooError(Exception):
message = u'An unknown exception occurred.'
def __str__(self):
if six.PY3:
return self.message
# Avoid UnicodeDecodeError in py2 when the string
# contains non-ASCII characters.
return self.message.encode('utf-8')
def __unicode__(self):
return self.message
# elsewhere...
def do_something():
raise FooError()
except FooError as ex:
# Returns a UTF-8 string in py2, and a wide string in py3,
# both of type six.text_type, with no coercion. Normally you
# would use six.text_type instead (see below)
msg_a = str(ex)
# Returns unicode type in py2 and str in py3.
msg_b = six.text_type(ex)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment