Unicode __repr__ and IPython

Unicode __repr__ and __str__ functions that return non-ascii characters result on my IPython installation in a stack trace. Try this:

In [1]: class Foo(object):
...:     def __repr__(self):
...:         return u"äöü"
...:

In [2]: Foo()
Out[2]: ---------------------------------------------------------------------------
UnicodeEncodeError                        Traceback (most recent call last)
<ipython-input-2-bbcd91f35259> in <module>()
----> 1 Foo()

... (several lines omitted)

/usr/lib/python2.7/dist-packages/IPython/lib/pretty.pyc in _default_pprint(obj, p, cycle)
    478     if getattr(klass, '__repr__', None) not in _baseclass_reprs:
    479         # A user-provided repr.
--> 480         p.text(repr(obj))
    481         return
    482     p.begin_group(1, '<')

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

The culprit is the default encoding of the output stream: While sys.stdout.encoding is UTF-8, sys.getdefaultencoding() returns ascii. The solution is to run the following code:

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

Insert this into your ipython_config.py (you may need to create it: ipython profile create) and the error goes away!