Skip to content

Instantly share code, notes, and snippets.

@kmike
Created June 27, 2012 16:43
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 kmike/3005316 to your computer and use it in GitHub Desktop.
Save kmike/3005316 to your computer and use it in GitHub Desktop.
import functools
class UnicodeMixin(object):
"""Mixin class to handle defining the proper __str__/__unicode__
methods in Python 2 or 3."""
if PY3:
def __str__(self):
return self.__unicode__()
else:
def __str__(self):
return self.__unicode__().encode('utf8')
def console_safe(func):
""" Decorator for making unicode functions console-friendly """
if PY3:
return func
@functools.wraps(func)
def inner(*args, **kwargs)
res = func(*args, **kwargs)
if isinstance(res, text_type): # XXX: use assert?
res = res.encode('unicode-escape')
return res
return inner
class SomeNltkClass(SomeNltkBase, UnicodeMixin):
# ...
def __unicode__(self):
return ...
@console_safe
def __repr__(self):
return self.__unicode__()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment