
On Thu, Mar 1, 2012 at 8:49 PM, Devin Jeanpierre <jeanpierreda@gmail.com>wrote:
On Thu, Mar 1, 2012 at 9:31 PM, Mark Janssen <dreamingforward@gmail.com> wrote:
I just thought of something: isn't the obvious solution is for doctest to test the type of an expression's output and if it's in the set of unordered types {set, dict} to run sort() on it? Then the docstring author can just put the (sorted) output of what's expected....
It's the solution people seem to think of first, so it's definitely fairly obvious. It's not a big improvement, though. The original problem is that dict order shouldn't matter, but in doctest it does, making dicts unusable in the normal doctest style. Making it a specific dict order be the prominent one lets you use dicts in doctest, but you have to sort the dicts and rewrite the doctest to take that into account.
Personally I never copy from the interactive prompt, but instead write my doctest and, if I'm in the mood to copy and paste, copy from the failed doctest error message (which is nicely indented just like my tests). So it would work fine if things were sorted.
And even so, some dicts cannot be represented this way. For example, the dict {1:2, "hello": world} cannot be sorted in Python 3, so it won't work in this scheme.
You could always use a heuristic sorting, e.g., sorted((str(key), key) for key in dict) To make this work you have to write a repr() replacement that is somewhat sophisticated. Though it still wouldn't save you from: class Something: def __repr__(self): return '<Something attr=%r>' % (self.attr) where attr is a dict or some other object with an awkward repr. That's the part I'm unsure of. Of course no eval will help you there either. I don't know if there's any way to really replace repr's implementation everywhere; I'm guessing there isn't. Ian