def _safe_repr(obj, context, maxlevels, level):
    typ = type(obj)
    if typ is str:
        if 'locale' not in sys.modules:
            return repr(obj)
        if "'" in obj and '"' not in obj:
            closure = '"'
            quotes = {'"': '\\"'}
        else:
            closure = "'"
            quotes = {"'": "\\'"}
        qget = quotes.get
        sio = BytesIO()
        write = sio.write
        for char in obj:
            if char.isalpha():
                write(char)
            else:
                write(qget(char, repr(char)[1:-1]))
        return ("%s%s%s" % (closure, sio.getvalue(), closure))

    if typ is dict:
        if not obj:
            return "{}"
        objid = id(obj)
        if maxlevels and level > maxlevels:
            return "{...}"
        if objid in context:
            return _recursion(obj)
        context[objid] = 1
        components = []
        append = components.append
        level += 1
        saferepr = _safe_repr
        for k, v in obj.iteritems():
            krepr = saferepr(k, context, maxlevels, level)
            vrepr = saferepr(v, context, maxlevels, level)
            append("%s: %s" % (krepr, vrepr))
        del context[objid]
        return "{%s}" % ", ".join(components)

    if typ is list or typ is tuple:
        if typ is list:
            if not obj:
                return "[]"
            format = "[%s]"
        elif len(obj) == 1:
            format = "(%s,)"
        else:
            if not obj:
                return "()"
            format = "(%s)"
        objid = id(obj)
        if maxlevels and level > maxlevels:
            return format % "..."
        if objid in context:
            return _recursion(obj)
        context[objid] = 1
        components = []
        append = components.append
        level += 1
        for o in obj:
            orepr = _safe_repr(o, context, maxlevels, level)
            append(orepr)
        del context[objid]
        return format % ", ".join(components)

    if typ is MethodType:
        return method_repr(obj)

    if typ is FunctionType:
        return function_repr(obj)

    return repr(obj)
dataset/ETHPy150Open kdart/pycopia/CLI/pycopia/UI.py/_safe_repr/original