Message73864
| Author |
idadesub |
| Recipients |
erickt, idadesub, pitrou |
| Date |
2008年09月26日.16:45:53 |
| SpamBayes Score |
1.86522e-05 |
| Marked as misclassified |
No |
| Message-id |
<1ef034530809260945s539ef046ne619db6244d0fc18@mail.gmail.com> |
| In-reply-to |
<1222445700.05.0.107288672735.issue3976@psf.upfronthosting.co.za> |
| Content |
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. |
|