Enum class with ToString functionality

Scott David Daniels Scott.Daniels at Acm.Org
Tue Sep 11 08:58:27 EDT 2007


bg_ie at yahoo.com wrote:
> Hi,
> 
> I have the following class -
> 
> class TestOutcomes:
>     PASSED = 0
>     FAILED = 1
>     ABORTED = 2
> 
> plus the following code -
> 
> testResult = TestOutcomes.PASSED
> 
> testResultAsString
> if  testResult == TestOutcomes.PASSED:
>     testResultAsString = "Passed"
> elif testResult == TestOutcomes.FAILED :
>     testResultAsString = "Failed"
> else:
>     testResultAsString = "Aborted"
> 
> But it would be much nicer if I had a function to covert to string as
> part of the TestOutcomes class. How would I implement this?
> 
> Thanks,
> 
> Barry
> 

     class Outcome(object):
         PASSED, FAILED, ABORTED = range(3)

         @classmethod
         def named(class_, value):
             for name in dir(class_):
                 if name[0] != '_' and getattr(class_, name) == value:
                     return name
             raise ValueError('Unknown value %r' % value)

     Outcome.named(2)


-Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list