Enum class with ToString functionality

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • bg_ie@yahoo.com

    Enum class with ToString functionality

    Hi,

    I have the following class -

    class TestOutcomes:
    PASSED = 0
    FAILED = 1
    ABORTED = 2

    plus the following code -

    testResult = TestOutcomes.PA SSED

    testResultAsStr ing
    if testResult == TestOutcomes.PA SSED:
    testResultAsStr ing = "Passed"
    elif testResult == TestOutcomes.FA ILED :
    testResultAsStr ing = "Failed"
    else:
    testResultAsStr ing = "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

  • Duncan Booth

    #2
    Re: Enum class with ToString functionality

    bg_ie@yahoo.com wrote:
    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?
    Perhaps: http://aspn.activestate.com/ASPN/Coo.../Recipe/413486

    Comment

    • David

      #3
      Re: Enum class with ToString functionality

      On 9/10/07, bg_ie@yahoo.com <bg_ie@yahoo.co mwrote:
      Hi,
      >
      I have the following class -
      >
      class TestOutcomes:
      PASSED = 0
      FAILED = 1
      ABORTED = 2
      >
      plus the following code -
      >
      testResult = TestOutcomes.PA SSED
      >
      testResultAsStr ing
      if testResult == TestOutcomes.PA SSED:
      testResultAsStr ing = "Passed"
      elif testResult == TestOutcomes.FA ILED :
      testResultAsStr ing = "Failed"
      else:
      testResultAsStr ing = "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?
      You can use reflection to do this. Perhaps a constructor that goes
      through your class dict (dir(self)) and builds an int->string mapping
      property based on the value and name of the attributes (perhaps just
      the ones whose type is int). To get the exact same result as your code
      above you can capitalize the first letter of the attribute name, and
      lowercase the rest.

      Comment

      • TheFlyingDutchman

        #4
        Re: Enum class with ToString functionality

        On Sep 10, 2:28 am, bg...@yahoo.com wrote:
        Hi,
        >
        I have the following class -
        >
        class TestOutcomes:
        PASSED = 0
        FAILED = 1
        ABORTED = 2
        >
        plus the following code -
        >
        testResult = TestOutcomes.PA SSED
        >
        testResultAsStr ing
        if testResult == TestOutcomes.PA SSED:
        testResultAsStr ing = "Passed"
        elif testResult == TestOutcomes.FA ILED :
        testResultAsStr ing = "Failed"
        else:
        testResultAsStr ing = "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
        The equivalent to Java's toString() is __str__() in Python:

        class TestOutcomes:
        PASSED = 0
        FAILED = 1
        ABORTED = 2

        def __init__(self,o utcome):
        self.outcome = outcome

        def __str__(self):
        if self.outcome == TestOutcomes.PA SSED:
        return "Passed"
        elif self.outcome == TestOutcomes.FA ILED :
        return "Failed"
        else:
        return "Aborted"

        if __name__ == "__main__":
        testResult = TestOutcomes(Te stOutcomes.ABOR TED)
        print testResult
        testResult = TestOutcomes(Te stOutcomes.FAIL ED)
        a = testResult.__st r__()
        print a

        Aborted
        Failed


        Comment

        • aine_canby@yahoo.com

          #5
          Re: Enum class with ToString functionality

          On 10 Sep, 13:35, TheFlyingDutchm an <zzbba...@aol.c omwrote:
          On Sep 10, 2:28 am, bg...@yahoo.com wrote:
          >
          >
          >
          >
          >
          Hi,
          >
          I have the following class -
          >
          class TestOutcomes:
          PASSED = 0
          FAILED = 1
          ABORTED = 2
          >
          plus the following code -
          >
          testResult = TestOutcomes.PA SSED
          >
          testResultAsStr ing
          if testResult == TestOutcomes.PA SSED:
          testResultAsStr ing = "Passed"
          elif testResult == TestOutcomes.FA ILED :
          testResultAsStr ing = "Failed"
          else:
          testResultAsStr ing = "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
          >
          The equivalent to Java's toString() is __str__() in Python:
          >
          class TestOutcomes:
          PASSED = 0
          FAILED = 1
          ABORTED = 2
          >
          def __init__(self,o utcome):
          self.outcome = outcome
          >
          def __str__(self):
          if self.outcome == TestOutcomes.PA SSED:
          return "Passed"
          elif self.outcome == TestOutcomes.FA ILED :
          return "Failed"
          else:
          return "Aborted"
          >
          if __name__ == "__main__":
          testResult = TestOutcomes(Te stOutcomes.ABOR TED)
          print testResult
          testResult = TestOutcomes(Te stOutcomes.FAIL ED)
          a = testResult.__st r__()
          print a
          >
          Aborted
          Failed- Dölj citerad text -
          >
          - Visa citerad text -
          Would this be crazy? -

          class TestOutcomes:
          PASSED = "PASSED"
          FAILED = "FAILED"
          ABORTED = "ABORTED"

          Comment

          • TheFlyingDutchman

            #6
            Re: Enum class with ToString functionality

            On Sep 10, 2:28 am, bg...@yahoo.com wrote:
            Hi,
            >
            I have the following class -
            >
            class TestOutcomes:
            PASSED = 0
            FAILED = 1
            ABORTED = 2
            >
            plus the following code -
            >
            testResult = TestOutcomes.PA SSED
            >
            testResultAsStr ing
            if testResult == TestOutcomes.PA SSED:
            testResultAsStr ing = "Passed"
            elif testResult == TestOutcomes.FA ILED :
            testResultAsStr ing = "Failed"
            else:
            testResultAsStr ing = "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 TestOutcomes:
            PASSED = 0
            FAILED = 1
            ABORTED = 2

            def ToString(outcom e):
            if outcome == TestOutcomes.PA SSED:
            return "Passed"
            elif outcome == TestOutcomes.FA ILED :
            return "Failed"
            else:
            return "Aborted"

            ToString = staticmethod(To String)

            if __name__ == "__main__":
            testResult = TestOutcomes.PA SSED
            testResultAsStr ing = TestOutcomes.To String(testResu lt)
            print testResultAsStr ing
            print TestOutcomes.To String(testResu lt)


            Passed
            Passed

            Comment

            • Bjoern Schliessmann

              #7
              Re: Enum class with ToString functionality

              bg_ie@yahoo.com wrote:
              I have the following class -
              >
              class TestOutcomes:
              PASSED = 0
              FAILED = 1
              ABORTED = 2
              >
              plus the following code -
              >
              testResult = TestOutcomes.PA SSED
              >
              testResultAsStr ing
              if testResult == TestOutcomes.PA SSED:
              testResultAsStr ing = "Passed"
              elif testResult == TestOutcomes.FA ILED :
              testResultAsStr ing = "Failed"
              else:
              testResultAsStr ing = "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?
              Why don't use the simple approach like this?

              TEST_PASSED = "Passed"
              TEST_FAILED = "Failed"
              TEST_ABORTED = "Aborted"

              In Python, no one forces you to put everything in classes.

              If you are determined to use the class approach, use the __str__
              method. It's called when you do str(instance).

              Regards,


              Björn

              --
              BOFH excuse #122:

              because Bill Gates is a Jehovah's witness and so nothing can work on
              St. Swithin's day.

              Comment

              • Bruno Desthuilliers

                #8
                Re: Enum class with ToString functionality

                TheFlyingDutchm an a écrit :
                On Sep 10, 2:28 am, bg...@yahoo.com wrote:
                >
                >>Hi,
                >>
                >>I have the following class -
                >>
                >>class TestOutcomes:
                > PASSED = 0
                > FAILED = 1
                > ABORTED = 2
                >>
                >>plus the following code -
                >>
                >>testResult = TestOutcomes.PA SSED
                >>
                >>testResultAsS tring
                >>if testResult == TestOutcomes.PA SSED:
                > testResultAsStr ing = "Passed"
                >>elif testResult == TestOutcomes.FA ILED :
                > testResultAsStr ing = "Failed"
                >>else:
                > testResultAsStr ing = "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 TestOutcomes:
                PASSED = 0
                FAILED = 1
                ABORTED = 2
                >
                def ToString(outcom e):
                if outcome == TestOutcomes.PA SSED:
                return "Passed"
                elif outcome == TestOutcomes.FA ILED :
                return "Failed"
                else:
                return "Aborted"
                >
                ToString = staticmethod(To String)
                >
                if __name__ == "__main__":
                testResult = TestOutcomes.PA SSED
                testResultAsStr ing = TestOutcomes.To String(testResu lt)
                print testResultAsStr ing
                print TestOutcomes.To String(testResu lt)
                >
                Technically correct, but totally unpythonic.

                May I suggest some reading ?

                Comment

                • TheFlyingDutchman

                  #9
                  Re: Enum class with ToString functionality

                  On Sep 8, 9:52 am, Bruno Desthuilliers
                  <bdesth.quelque ch...@free.quel quepart.frwrote :
                  TheFlyingDutchm an a écrit :
                  >
                  >
                  >
                  On Sep 10, 2:28 am, bg...@yahoo.com wrote:
                  >
                  >Hi,
                  >
                  >I have the following class -
                  >
                  >class TestOutcomes:
                  PASSED = 0
                  FAILED = 1
                  ABORTED = 2
                  >
                  >plus the following code -
                  >
                  >testResult = TestOutcomes.PA SSED
                  >
                  >testResultAsSt ring
                  >if testResult == TestOutcomes.PA SSED:
                  testResultAsStr ing = "Passed"
                  >elif testResult == TestOutcomes.FA ILED :
                  testResultAsStr ing = "Failed"
                  >else:
                  testResultAsStr ing = "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 TestOutcomes:
                  PASSED = 0
                  FAILED = 1
                  ABORTED = 2
                  >
                  def ToString(outcom e):
                  if outcome == TestOutcomes.PA SSED:
                  return "Passed"
                  elif outcome == TestOutcomes.FA ILED :
                  return "Failed"
                  else:
                  return "Aborted"
                  >
                  ToString = staticmethod(To String)
                  >
                  if __name__ == "__main__":
                  testResult = TestOutcomes.PA SSED
                  testResultAsStr ing = TestOutcomes.To String(testResu lt)
                  print testResultAsStr ing
                  print TestOutcomes.To String(testResu lt)
                  >
                  Technically correct, but totally unpythonic.
                  Speaking of unpythonic, I would call

                  ToString = staticmethod(To String)

                  A Perlific syntax.
                  Well the Foo.Foo complaint is bogus:

                  from Foo import Foo

                  Comment

                  • Ben Finney

                    #10
                    Re: Enum class with ToString functionality

                    bg_ie@yahoo.com writes:
                    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?
                    Others have given ad hoc implementations that may do what you want.

                    I'd like to know if the Cheeseshop package 'enum' is useful to
                    you. Any constructive feedback would be appreciated.

                    <URL:http://cheeseshop.pyth on.org/pypi/enum/>

                    --
                    \ "Remorse: Regret that one waited so long to do it." -- Henry |
                    `\ L. Mencken |
                    _o__) |
                    Ben Finney

                    Comment

                    • Bruno Desthuilliers

                      #11
                      Re: Enum class with ToString functionality

                      TheFlyingDutchm an a écrit :
                      On Sep 8, 9:52 am, Bruno Desthuilliers
                      <bdesth.quelque ch...@free.quel quepart.frwrote :
                      >
                      >>TheFlyingDutc hman a écrit :
                      (snip)
                      >>>class TestOutcomes:
                      >> PASSED = 0
                      >> FAILED = 1
                      >> ABORTED = 2
                      >>
                      >> def ToString(outcom e):
                      >> if outcome == TestOutcomes.PA SSED:
                      >> return "Passed"
                      >> elif outcome == TestOutcomes.FA ILED :
                      >> return "Failed"
                      >> else:
                      >> return "Aborted"
                      >>
                      >> ToString = staticmethod(To String)
                      >>
                      (snip)
                      >>Technically correct, but totally unpythonic.
                      >
                      >
                      Speaking of unpythonic, I would call
                      >
                      ToString = staticmethod(To String)
                      >
                      A Perlific syntax.
                      Nope, just a good ole HOF.

                      But nowadays, it's usually written this way:

                      @staticmethod
                      def some_static_met hod():
                      pass
                      >>
                      Well the Foo.Foo complaint is bogus:
                      >
                      from Foo import Foo
                      >
                      Yes. And properties are bogus - just use getters and setters.

                      Seriously, writing Java in Python is definitively on the masochist side.
                      But if you like pain...

                      Comment

                      • Zara

                        #12
                        Re: Enum class with ToString functionality

                        On Mon, 10 Sep 2007 02:28:57 -0700, bg_ie@yahoo.com wrote:
                        >Hi,
                        >
                        >I have the following class -
                        >
                        >class TestOutcomes:
                        PASSED = 0
                        FAILED = 1
                        ABORTED = 2
                        >
                        >plus the following code -
                        >
                        >testResult = TestOutcomes.PA SSED
                        >
                        >testResultAsSt ring
                        >if testResult == TestOutcomes.PA SSED:
                        testResultAsStr ing = "Passed"
                        >elif testResult == TestOutcomes.FA ILED :
                        testResultAsStr ing = "Failed"
                        >else:
                        testResultAsStr ing = "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?
                        >
                        You should implement __str__ (or __repr__) method in your class,

                        class TestOutcomes:
                        PASSED = 0
                        FAILED = 1
                        ABORTED = 2

                        def __str__(self):
                        textResultAsStr ing="Unknown"
                        if testResult == TestOutcomes.PA SSED:
                        testResultAsStr ing = "Passed"
                        elif testResult == TestOutcomes.FA ILED :
                        testResultAsStr ing = "Failed"
                        else:
                        testResultAsStr ing = "Aborted"
                        return testResultAsStr ing

                        Regards,

                        Zara

                        Comment

                        • Ben Finney

                          #13
                          Version numbering (was: Enum class with ToString functionality)

                          TheFlyingDutchm an <zzbbaadd@aol.c omwrites:
                          On Sep 10, 7:55 pm, "J. Cliff Dyer" <j...@sdf.lones tar.orgwrote:
                          Uh... The 1.0 version is vaporware?
                          >
                          I think not. 42% of it is alive and kicking as we speak.
                          That's odd. Do you think some similar matchematical relationship
                          exists between Python version 2.4.4 and 3.0?

                          You've made the common error of reading a package version as though it
                          were a single number on a number line. That's not the customary
                          semantic, though: versions are interpreted as a tuple of distinct
                          integers.
                          When you were developing your Enum module, how did you determine you
                          were at the 0.4.2 version as opposed to the 0.7.1 version or the
                          0.9.2 version?
                          I initially developed at version 0.0, meaning "major level 0, minor
                          level 0" — i.e., no releases at all.

                          Then, when the first "alpha" release was ready, I called it version
                          0.1, meaning "major level 0, minor level 1" — i.e. no major releases
                          yet, but the first minor release.

                          Then, a small patch needed to be made, and the resulting release was
                          version 0.1.1, meaning "major level 0, minor level 1, patch level 1" —
                          i.e. the first patch to version 0.1.

                          Eventually some extra features warranted a release of version 0.2,
                          meaning "major level 0, minor level 2" — i.e. the second minor release
                          with still no major releases. Implicit in this is "patch level 0",
                          i.e. no patch-level versions yet; the version could be called 0.2.0
                          and have the same meaning.

                          Each dot-separated integer is interpreted as a distinct level,
                          subordinate to the preceding one:

                          * Two versions with different major numbers can be expected to be
                          incompatible.

                          * If two versions have the same major number, one can expect only
                          minor feature differences.

                          * If two versions have the same major and minor number, one can
                          expect that they differ only in bug fixes or the like.

                          * Subsequent integers would imply even smaller differences at that
                          same level if all preceding numbers were the same.

                          Within a level, subsequent integers imply subsequent release times:
                          version 0.4.1 can only be released before 0.4.2. However, this is not
                          true across levels: a hypothetical version 0.2.7 could be released
                          before *or* after 0.4.2, if the author decides a patch to the (equally
                          hypothetical) version 0.2.6 is warranted.

                          As for a putative version 1.0, that will not be released until I
                          determine the package is functionally complete and warrants a first
                          major release. Depending on how much changes between now and then, it
                          may have most, some, or none of the code you see presently in version
                          0.4.2.

                          --
                          \ "That's all very good in practice, but how does it work in |
                          `\ *theory*?" —Anonymous |
                          _o__) |
                          Ben Finney

                          Comment

                          • J. Cliff Dyer

                            #14
                            Re: Enum class with ToString functionality

                            Zara wrote:
                            On Mon, 10 Sep 2007 02:28:57 -0700, bg_ie@yahoo.com wrote:
                            >
                            >
                            >Hi,
                            >>
                            >I have the following class -
                            >>
                            >class TestOutcomes:
                            > PASSED = 0
                            > FAILED = 1
                            > ABORTED = 2
                            >>
                            >plus the following code -
                            >>
                            >testResult = TestOutcomes.PA SSED
                            >>
                            >testResultAsSt ring
                            >if testResult == TestOutcomes.PA SSED:
                            > testResultAsStr ing = "Passed"
                            >elif testResult == TestOutcomes.FA ILED :
                            > testResultAsStr ing = "Failed"
                            >else:
                            > testResultAsStr ing = "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?
                            >>
                            >>
                            You should implement __str__ (or __repr__) method in your class,
                            >
                            class TestOutcomes:
                            PASSED = 0
                            FAILED = 1
                            ABORTED = 2
                            >
                            def __str__(self):
                            textResultAsStr ing="Unknown"
                            if testResult == TestOutcomes.PA SSED:
                            testResultAsStr ing = "Passed"
                            elif testResult == TestOutcomes.FA ILED :
                            testResultAsStr ing = "Failed"
                            else:
                            testResultAsStr ing = "Aborted"
                            return testResultAsStr ing
                            >
                            Regards,
                            >
                            Zara
                            >
                            >
                            This code cannot output "Unknown," because you use an else: at the end
                            of your if-chain to represent a specific (non-catch-all) case.

                            s/else:/elif testResult == TestOutcomes.AB ORTED:/

                            Cheers,
                            Cliff

                            Comment

                            • Scott David Daniels

                              #15
                              Re: Enum class with ToString functionality

                              bg_ie@yahoo.com wrote:
                              Hi,
                              >
                              I have the following class -
                              >
                              class TestOutcomes:
                              PASSED = 0
                              FAILED = 1
                              ABORTED = 2
                              >
                              plus the following code -
                              >
                              testResult = TestOutcomes.PA SSED
                              >
                              testResultAsStr ing
                              if testResult == TestOutcomes.PA SSED:
                              testResultAsStr ing = "Passed"
                              elif testResult == TestOutcomes.FA ILED :
                              testResultAsStr ing = "Failed"
                              else:
                              testResultAsStr ing = "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('Unk nown value %r' % value)

                              Outcome.named(2 )


                              -Scott David Daniels
                              Scott.Daniels@A cm.Org

                              Comment

                              Working...