Created
December 13, 2013 21:28
-
-
Save kgriffs/7951625 to your computer and use it in GitHub Desktop.
Python 3.3 compatible magic string methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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