[Tutor] doctest question

Steven D'Aprano steve at pearwood.info
Tue Nov 27 15:01:21 CET 2012


On 27/11/12 20:50, Albert-Jan Roskam wrote:

>> Function name "_setMultRespDefsEx" is not self-explanatory, or even
>> *hint* at what the function is supposed to do. It appears to take a
>> dictionary of stuff, and formats it as a string. It would be nice[1]
>> if your docstring explained what sort of stuff.
>
> But in my defense (a little bit, at least), this is a helper
> function for another function that *does* have a good explanation/docstring.
> I should mention that in this function's docstring though.

Yes!

You're not just writing documentation for others. You're also writing
documentation for yourself, in six months time, or even six weeks time,
when the function is no longer fresh in your mind and you only have the
vaguest memory of what it is supposed to do.


[...]
>> Doctesting anything to do with dictionaries is tricky, because you
>> cannot rely on the order of a dict. There are a couple of different
>> ways to solve that:
>
> Huh? Although I am iterating over a dictionary (which is unordered),
> the return value will, given a certain input, always be the same. Why
> is the 'unorderedness' relevant here?

Because if you don't sort the dictionary items, the doctest fails. I
know this, because the first time I ran it, it failed for exactly this
reason.

Feel free to take the call to sorted() out. When you do, your input
dict looks like this:

{'mesetx': ..., 'mesety': ...}  # X first, Y second

and your doctest, *as you wrote it*, has the same order:

$mesetx= ...
$mesety= ...


BUT the actual output of the function may be in the opposite order,
Y first and X second.

Or at least, that's the order *I* get, running CPython 2.7.2 under
Centos Linux built with gcc 4.1.2. What *you* get, running some
other version of Python, built with a different compiler, under a
different operating system, may be different.

With only two items in the dict, you have a 50% chance of the
doctest matching the actual run of the dict.

The only promise that Python makes about the order of iterating
over a dict is that if you iterate over the same dict twice,
without making any changes, in the same Python run, you will get
the same output. That is all.

You might get a different order if you do any of these things:

- modify the dict between runs, even if you reverse the changes;

- change the way you assemble the dict in the first place;

- use a different version of Python;

- or a different implementation;

- or theoretically even the same version but on a different OS;

- or even if you merely exit Python and run the script again.

[steve at ando ~]$ python3.3 -c "print({'a': None, 'b': None})"
{'b': None, 'a': None}
[steve at ando ~]$ python3.3 -c "print({'a': None, 'b': None})"
{'a': None, 'b': None}



-- 
Steven


More information about the Tutor mailing list