Code style query: multiple assignments in if/elif tree

Ian Kelly ian.g.kelly at gmail.com
Tue Apr 1 02:28:53 EDT 2014


On Mon, Mar 31, 2014 at 11:45 PM, Rustom Mody <rustompmody at gmail.com> wrote:
> On Tue, Apr 1, 2014 at 3:26 PM, Steven D'Aprano  wrote:
>
>> Haskell has nifty pattern-matching syntax for this that looks quite close
>> to the mathematical hybrid function syntax, but in Python, we're limited
>> to explicitly using an if. If I were coding this, and I'm not, I'd wrap
>> it in a function. One advantage of a state variable rather than a
>> continuous time function is that we can do this:
>> def accel(state):
>>     return {NO_BRAKING: 0.0,
>>             LOW_BRAKING: 0.2,
>>             MID_BRAKING: 0.425,
>>             HIGH_BRAKING: 0.85}[state]
>
> Neat
> I would put the dict in a variable. And those _BRAKINGs are GALLing me!
>
> breaking = {NO:0.0, LOW:0.2, MID:0.425:, HIGH:0.85}
> def accel(state): return breaking[state]

If I were doing this in Python 3.4 I would be sorely tempted to use an
Enum for the state.  Then the acceleration could just be an attribute
(or method) of the state itself!

class BrakingState(Enum):
    no_braking = 0.0
    low_braking = 0.2
    mid_braking = 0.425
    high_braking = 0.85

    @property
    def acceleration(self):
        return self.value

>>> print(BrakingState.low_braking.acceleration)
0.2


Alternatively the __init__ method could set the acceleration directly
from the value(s) passed in, as in the Planet example:

https://docs.python.org/3/library/enum.html#planet

The problem I have with either of these approaches though is that if
two distinct states happen to have the same acceleration, they will be
considered aliases for the same state.  This is because the
acceleration value is doing double duty as a parameter of the state
and also as its identity.  Likewise in the Planet example, if a new
planet happened to have the same mass and radius as Jupiter, it would
be considered the same planet as Jupiter. I haven't managed to work
out a wholly satisfying way to avoid this.



More information about the Python-list mailing list