On Wed, Oct 8, 2014 at 8:34 PM, Rustom Mody <rustompm...@gmail.com> 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 > <Color.Red: 0> >>>> 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 > <Color.Blue: 1> >>>> > >>>> # Better >>>> def toggle(c): return Color.Blue if c==Color.Red else Color.Red > ... >>>> toggle(c) > <Color.Blue: 1> >>>> toggle(c) > <Color.Blue: 1> > > # 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.red: 0> >>> Color.blue.toggle().toggle() <Color.blue: 1> (Note the recommended way to compare enum instances is with "is", not "==".) -- https://mail.python.org/mailman/listinfo/python-list