Message73864
fyi, I found another case where pprint needs a "safe sort", this is
when you have a list that contains a dictionary. Anyway, Here's a
simple patch that creates a _safe_sorted function that implements the
fallback:
--- /opt/local/lib/python3.0/pprint.py 2008-09-26 09:35:21.000000000 -0700
+++ /tmp/pprint.py 2008-09-26 09:35:13.000000000 -0700
@@ -145,7 +145,7 @@
if length:
context[objid] = 1
indent = indent + self._indent_per_level
- items = sorted(object.items())
+ items = _safe_sorted(object.items())
key, ent = items[0]
rep = self._repr(key, context, level)
write(rep)
@@ -267,14 +267,7 @@
append = components.append
level += 1
saferepr = _safe_repr
- items = object.items()
- try:
- items = sorted(items)
- except TypeError:
- def sortkey(item):
- key, value = item
- return str(type(key)), key, value
- items = sorted(items, key=sortkey)
+ items = _safe_sorted(object.items())
for k, v in items:
krepr, kreadable, krecur = saferepr(k, context, maxlevels, level)
vrepr, vreadable, vrecur = saferepr(v, context, maxlevels, level)
@@ -321,6 +314,20 @@
rep = repr(object)
return rep, (rep and not rep.startswith('<')), False
+def _safe_sorted(items):
+ try:
+ return sorted(items)
+ except TypeError:
+ def sortkey(item):
+ key, value = item
+ return str(type(key)), key, value
+ try:
+ return sorted(items, key=sortkey)
+ except TypeError:
+ def sortkey(item):
+ key, value = item
+ return str(type(key))
+ return sorted(items, key=sortkey)
def _recursion(object):
return ("<Recursion on %s with id=%s>"
One other thing to note is that I'm also aware that the yaml project
also has this problem, and they've got their own "safe_sorted"
function. It might be worthwhile formalizing this in a public function
in the api somewhere. |
|
Date |
User |
Action |
Args |
2008-09-26 16:45:54 | idadesub | set | recipients:
+ idadesub, pitrou, erickt |
2008-09-26 16:45:53 | idadesub | link | issue3976 messages |
2008-09-26 16:45:53 | idadesub | create | |
|