Comparisons and sorting of a numeric class....

Rustom Mody rustompmody at gmail.com
Fri Jan 23 22:13:00 EST 2015


On Friday, January 23, 2015 at 11:35:49 PM UTC+5:30, Ian wrote:
> On Fri, Jan 23, 2015 at 10:03 AM, Rustom Mody wrote:
> > On Friday, January 23, 2015 at 10:22:06 PM UTC+5:30, Ian wrote:
> >> On Fri, Jan 23, 2015 at 8:31 AM, Rustom Mody wrote:
> >> > Can you tell me what of the following code does not satisfy your requirements?
> >> > [Needs python 3.4]
> >> >
> >> >
> >> >>>> from enum import IntEnum
> >> >>>> class B4(IntEnum):
> >> >         F1 = 0
> >> >         F2 = 0
> >> >         F3 = 0
> >> >         T  = 1
> >>
> >> This strikes me as a potential problem:
> >>
> >> >>> B4.F1 is B4.F2 is B4.F3
> >> True
> >> >>> list(B4)
> >> [<B4.F1: 0>, <B4.T: 1>]
> >>
> >> Enum members with the same values are just aliases for one another,
> >> not distinct entities.
> >
> > Yeah....
> >
> > The only workaround I have been able to come up with is:
> >
> > class B4(IntEnum):
> >>         F1 = 0
> >>         F2 = ""
> >>         F3 = None
> >>         T  = 1
> >
> > which is not bad; its ridiculous
> > [Like going around with a broken broom searching for falsey objects :-) ]
> 
> How about something like this:
> 
> >>> from enum import Enum
> >>> class B4(Enum):
> ...     F1 = (False, 1)
> ...     F2 = (False, 2)
> ...     F3 = (False, 3)
> ...     T = (True, 4)
> ...     def __bool__(self):
> ...         return self.value[0]
> ...
> >>> B4.F1 is B4.F2
> False
> >>> bool(B4.F1)
> False
> >>> bool(B4.T)
> True

‼Perfect‼
For the OP you may like to read the following:

[And if you dont short version is use __bool__ in python3 __nonzero__ in python2
]

http://stackoverflow.com/questions/8909932/how-to-overload-pythons-bool-method
http://stackoverflow.com/questions/2233786/overriding-bool-for-custom-class
https://docs.python.org/2/reference/datamodel.html#object.__nonzero__



More information about the Python-list mailing list