#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re

def literalize_string(content, is_unicode=False):
    '''Literalize a string content.

    Examples:

    >>> print literalize_string('str')
    'str'
    >>> print literalize_string('\'str\'')
    "'str'"
    >>> print literalize_string('\"\'str\'\"')
    '"\'str\'"'
    '''

    quote_mark = "'"
    if "'" in content:
        quote_mark = '"'
        if '"' in content:
            quote_mark = "'"
            content = content.replace(r"'", r"\'")

    return 'u'[not is_unicode:]+quote_mark+content+quote_mark

string_literal_re = re.compile(r'''[uU]?(?P<q>['"]).+?(?<!\\)(?P=q)''')

def unescape_string_literal(literal, encoding):
    '''Unescape a string or unicode literal.

    Examples:

    >>> u = u'世界你好'
    >>> print unescape_string_literal(repr(u), 'utf-8')
    u'世界你好'

    >>> print unescape_string_literal(repr(u.encode('utf-8')), 'utf-8')
    '世界你好'

    >>> print unescape_string_literal(repr(u.encode('big5')), 'utf-8')
    '\xa5@\xac\xc9\xa7a\xa6n'
    '''

    if literal[0] in 'uU':

        return literalize_string(
            literal[2:-1].decode('unicode-escape').encode(encoding),
            is_unicode=True
        )

    else:

        content = literal[1:-1].decode('string-escape')

        # keep it escaped if the encoding doesn't work on it
        try:
            content.decode(encoding)
        except UnicodeDecodeError:
            return literal

    return literalize_string(content)

def unescape(b, encoding):
    '''Unescape all string and unicode literals in bytes.'''
    return string_literal_re.sub(lambda m: unescape_string_literal(m.group(), encoding), b)

def make_unistream(stream):
    '''Make a stream which unescapes string literals before writes out.'''

    unistream = lambda: 'I am an unistream!'

    # make unistream look like the stream
    for attr_name in dir(stream):
        if not attr_name.startswith('_'):
            setattr(unistream, attr_name, getattr(stream, attr_name))

    # modify the write method to unescape the output
    unistream.write = lambda b: stream.write(unescape(b, unistream.encoding))

    return unistream

def runs_in_ipython():
    '''Check if we are in IPython.'''
    import __builtin__
    return '__IPYTHON__' in __builtin__.__dict__ and \
           __builtin__.__dict__['__IPYTHON__']

@@ -105,16 +105,17 @@
 e):%0A    
+r
 '''Liter
@@ -687,32 +687,33 @@
  encoding):%0A    
+r
 '''Unescape a st
@@ -767,21 +767,48 @@
 %3E u = u'
+%5Cu4e16%5Cu754c%5Cu4f60%5Cu597d' # 
 %E4%B8%96%E7%95%8C%E4%BD%A0%E5%A5%BD
-'
 %0A    %3E%3E%3E
@@ -1046,17 +1046,17 @@
 %5Cxc9%5Cxa7
-a
+A
 %5Cxa6n'%0A 
@@ -2374,8 +2374,77 @@
 HON__'%5D%0A
+%0Aif __name__ == '__main__':%0A    import doctest%0A    doctest.testmod()%0A

use doctest