get a unicode safe string representation of an object
(object, encoding=None)
| 130 | |
| 131 | |
| 132 | def tostr(object, encoding=None): |
| 133 | """ get a unicode safe string representation of an object """ |
| 134 | if isinstance(object, basestring): |
| 135 | if encoding is None: |
| 136 | return object |
| 137 | else: |
| 138 | return object.encode(encoding) |
| 139 | if isinstance(object, tuple): |
| 140 | s = ['('] |
| 141 | for item in object: |
| 142 | if isinstance(item, basestring): |
| 143 | s.append(item) |
| 144 | else: |
| 145 | s.append(tostr(item)) |
| 146 | s.append(', ') |
| 147 | s.append(')') |
| 148 | return ''.join(s) |
| 149 | if isinstance(object, list): |
| 150 | s = ['['] |
| 151 | for item in object: |
| 152 | if isinstance(item, basestring): |
| 153 | s.append(item) |
| 154 | else: |
| 155 | s.append(tostr(item)) |
| 156 | s.append(', ') |
| 157 | s.append(']') |
| 158 | return ''.join(s) |
| 159 | if isinstance(object, dict): |
| 160 | s = ['{'] |
| 161 | for item in object.items(): |
| 162 | if isinstance(item[0], basestring): |
| 163 | s.append(item[0]) |
| 164 | else: |
| 165 | s.append(tostr(item[0])) |
| 166 | s.append(' = ') |
| 167 | if isinstance(item[1], basestring): |
| 168 | s.append(item[1]) |
| 169 | else: |
| 170 | s.append(tostr(item[1])) |
| 171 | s.append(', ') |
| 172 | s.append('}') |
| 173 | return ''.join(s) |
| 174 | try: |
| 175 | return unicode(object) |
| 176 | except: |
| 177 | return str(object) |
| 178 | |
| 179 | |
| 180 | class null: |