[Tutor] doctest question
Dave Angel
d at davea.name
Tue Nov 27 13:09:54 CET 2012
On 11/27/2012 04:50 AM, Albert-Jan Roskam wrote:
>
>> On 27/11/12 08:06, Albert-Jan Roskam wrote:
>>> (Steven D'Aprano wrote, even though the indentation is wrong)
>>>
>>>
>>>
>>> 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?
>
It's only promised to be the same for a single run of the program.
http://permalink.gmane.org/gmane.comp.python.devel/131826
In particular, """
Hash randomization causes the iteration order of dicts and sets to be
unpredictable and differ across Python runs. Python has never guaranteed
iteration order of keys in a dict or set, and applications are advised to never
rely on it. Historically, dict iteration order has not changed very often across
releases and has always remained consistent between successive executions of
Python."""
Starting with the releases described in that document, hash randomization was introduced, but disabled by default. But a user might enable it (with the -R cmd switch, or an environment variable). And in the latest version (3.3, i believe it's enabled by default, as a protection against a security threat.
Even if you somehow can assure that your code will never run on those versions, it has never been assured that the hash ordering remains stable between even minor versions of the releases.
> (Steven again:)
>> * the lazy solution: always use doctests on dicts with a single item;
>>
>> * change the function to always process the dict in a known order;
>>
>> * change the doctest to post-process the function result, e.g. pull
>> the string apart into separate lines, sort the lines, put it
>> back together.
>>
>>
>>
As Steven points out, it's dangerous to doctest with a dictionary
without some form of enforced ordering.
--
DaveA
More information about the Tutor
mailing list