Skip to content

Instantly share code, notes, and snippets.

@kgriffs
Created December 13, 2013 21:28
Show Gist options
  • Save kgriffs/7951625 to your computer and use it in GitHub Desktop.
Save kgriffs/7951625 to your computer and use it in GitHub Desktop.
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()
try:
do_something()
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