Toggle
Rustom Mody
rustompmody at gmail.com
Thu Oct 9 12:33:30 EDT 2014
On Thursday, October 9, 2014 9:39:07 PM UTC+5:30, Ian wrote:
> On Wed, Oct 8, 2014 at 8:34 PM, Rustom Mody wrote:
> > On Thursday, October 9, 2014 7:12:41 AM UTC+5:30, Ben Finney wrote:
> >> Seymore4Head writes:
> >> > I want to toggle between color="Red" and color="Blue"
> >> It's good to cultivate ongoing familiarity with the standard library
> > And language. In recent python3:
> >>>> class Color(Enum):
> > ... Red = 0
> > ... Blue = 1
> > ...
> >>>> Color.Red
> >>>> print (Color.Red)
> > Color.Red
> > # Not sure what to make of that distinction...
> >>>> c=Color.Red
> >>>> c = Color.Blue if c==Color.Red else Color.Red
> >>>> c
> >>>> # Better
> >>>> def toggle(c): return Color.Blue if c==Color.Red else Color.Red
> > ...
> >>>> toggle(c)
> >>>> toggle(c)
> > # which means the c has not changed
> Python enums can have methods and properties, which means that toggle
> could be implemented as such:
> >>> class Color(Enum):
> ... red = 0
> ... blue = 1
> ... def toggle(self):
> ... return Color.blue if self is Color.red else Color.red
> ...
> >>> Color.blue.toggle()
> >>> Color.blue.toggle().toggle()
Nice!
In fact this:
> >>> Color.blue.toggle()
> <Color.red: 0>
> >>> Color.blue.toggle().toggle()
> <Color.blue: 1>
is a nice example of a pattern that is rarely seen:
OO syntax, functional (ie non-state-changing) semantics.
It would have been even nicer were this acceptable [Its not :-( ]
>>> class Color(Enum):
... red = 0
... blue = 1
... def toggle(self):
... return blue if self is red else red
> (Note the recommended way to compare enum instances is with "is", not "==".)
Umm... I know...
Im in Lent -- fasting off contentious territories.
[You may remember that I'd rather avoid 'is']
More information about the Python-list
mailing list