Reputation: 11
I was upgrading a codebase from Python 2 to Python 3.
The test cases fail in Python 3 code because the set()
function produces a different order from Python 2.
For example;
# Here in Python 2.7 the PYTHONHASHSEED is disabled.
list = {"it","is","rishabh","Mishra"}
# Below, in Python 3
list = {"rishabh","it","is","mishra"}
I want the order to stay consistent with Python 2.7 so as to pass the test cases.
In Python 3.3 above, PYTHONHASHSEED=0
disables the random shuffling but it does not yield the same order as Python 2.7.
How can I use PYTHONHASHSEED
and maintain the order in Python 3?
Upvotes: 1
Views: 261
Reputation: 10030
You should not ever reckon on particular set ordering. Set is an unordered collection:
Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.
If your tests rely on it, they are just wrong. If you want to have a "set" with particular ordering, you should use tuples or lists and check uniquness of elements. Or you can implement your own OrderedSet based on MutableSet.
Upvotes: 2