On 2018-07-05 18:57, Steven D'Aprano wrote:
I have a function which returns a dict, and I want to use doctest to
ensure the documentation is correct. So I write a bunch of doctests:

def func(arg):
     """blah blah blah

     >>> func(1)
     {'a': 1, 'b': 2, 'c': 3}
     """

which is correct, *except* that dict keys have arbitrary order in the
versions of Python I'm using.

I have three ways of dealing with this. Which do you prefer?


1. Re-write the doctest to compare with another dict:

         >>> actual = func(1)
         >>> expected = {'a': 1, 'b': 2, 'c': 3}
         >>> actual == expected
         True

I don't like that because it obscures the clear relationship between
"call the function" -> "here's the output you get".



2. Use a pretty-printer function that cleverly sorts the keys before
printing:

     >>> _ppr(func(1))
     {'a': 1, 'b': 2, 'c': 3}

I don't like that, because the call to the pretty printer obscures the
call to the function.



3. I thought, "what a pity I can't move the pretty printer to the end od
the line, instead of the beginning, to reduce the emphasis on it". And
then I thought, yes I can!" and re-wrote the pretty printer to use the
__ror__ method instead:

     >>> func(1) | _ppr
     {'a': 1, 'b': 2, 'c': 3}


I think that's really clever. Is it too clever? How do you deal with
dicts in doctests?


(Ensuring that the dicts only have a single item is not feasible.)

What about sorting the items?

def func(arg):
     """blah blah blah

     >>> sorted(func(1).items())
     [('a', 1), ('b', 2), ('c', 3)]
     """
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to