I like using dictionaries as a form of switch statment, by settings booleans as keys. Example:
>>> def f(a):
... return {True: -a, a==0: 0, a > 0: a}[True]
...
>>> f(-3)
3
>>> f(3)
3
>>> f(0)
0
The key True works as an else/default case and is only returned if no other key is evaluated to True. I am guessing this assumes some sort of order of evaluation for iterating the dictionary.
Now look at the following extract from the latest release announcement from the Python team for the newest versions of branches 2.6, 2.7, 3.1 and 3.2:
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. Thus, some
existing applications may be relying on dict or set ordering.
Does this mean that using dicts as switch calls will not be possible anymore? Or maybe I should use any other class (like OrderedDict or something)? Or maybe I’m completely off and it should not affect this at all?
You misunderstood how this code works.
Your dictionary has only two keys:
TrueandFalse. There could be multiple conflicting values for theTruekey but that gets resolved at the initialization of the dictionary.There’s no iteration for a dictionary lookup.