473,382 Members | 1,353 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

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.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

Sep 10 '07 #1
15 2965
bg***@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
Sep 10 '07 #2
On 9/10/07, bg***@yahoo.com <bg***@yahoo.comwrote:
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?
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.
Sep 10 '07 #3
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.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
The equivalent to Java's toString() is __str__() in Python:

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

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

def __str__(self):
if self.outcome == TestOutcomes.PASSED:
return "Passed"
elif self.outcome == TestOutcomes.FAILED :
return "Failed"
else:
return "Aborted"

if __name__ == "__main__":
testResult = TestOutcomes(TestOutcomes.ABORTED)
print testResult
testResult = TestOutcomes(TestOutcomes.FAILED)
a = testResult.__str__()
print a

Aborted
Failed
Sep 10 '07 #4
On 10 Sep, 13:35, TheFlyingDutchman <zzbba...@aol.comwrote:
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.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

The equivalent to Java's toString() is __str__() in Python:

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

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

def __str__(self):
if self.outcome == TestOutcomes.PASSED:
return "Passed"
elif self.outcome == TestOutcomes.FAILED :
return "Failed"
else:
return "Aborted"

if __name__ == "__main__":
testResult = TestOutcomes(TestOutcomes.ABORTED)
print testResult
testResult = TestOutcomes(TestOutcomes.FAILED)
a = testResult.__str__()
print a

Aborted
Failed- Dölj citerad text -

- Visa citerad text -
Would this be crazy? -

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

Sep 10 '07 #5
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.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 TestOutcomes:
PASSED = 0
FAILED = 1
ABORTED = 2

def ToString(outcome):
if outcome == TestOutcomes.PASSED:
return "Passed"
elif outcome == TestOutcomes.FAILED :
return "Failed"
else:
return "Aborted"

ToString = staticmethod(ToString)

if __name__ == "__main__":
testResult = TestOutcomes.PASSED
testResultAsString = TestOutcomes.ToString(testResult)
print testResultAsString
print TestOutcomes.ToString(testResult)
Passed
Passed

Sep 10 '07 #6
bg***@yahoo.com wrote:
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?
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.

Sep 10 '07 #7
TheFlyingDutchman 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.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 TestOutcomes:
PASSED = 0
FAILED = 1
ABORTED = 2

def ToString(outcome):
if outcome == TestOutcomes.PASSED:
return "Passed"
elif outcome == TestOutcomes.FAILED :
return "Failed"
else:
return "Aborted"

ToString = staticmethod(ToString)

if __name__ == "__main__":
testResult = TestOutcomes.PASSED
testResultAsString = TestOutcomes.ToString(testResult)
print testResultAsString
print TestOutcomes.ToString(testResult)
Technically correct, but totally unpythonic.

May I suggest some reading ?
http://dirtsimple.org/2004/12/python-is-not-java.html
Sep 10 '07 #8
On Sep 8, 9:52 am, Bruno Desthuilliers
<bdesth.quelquech...@free.quelquepart.frwrote:
TheFlyingDutchman 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.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 TestOutcomes:
PASSED = 0
FAILED = 1
ABORTED = 2
def ToString(outcome):
if outcome == TestOutcomes.PASSED:
return "Passed"
elif outcome == TestOutcomes.FAILED :
return "Failed"
else:
return "Aborted"
ToString = staticmethod(ToString)
if __name__ == "__main__":
testResult = TestOutcomes.PASSED
testResultAsString = TestOutcomes.ToString(testResult)
print testResultAsString
print TestOutcomes.ToString(testResult)

Technically correct, but totally unpythonic.
Speaking of unpythonic, I would call

ToString = staticmethod(ToString)

A Perlific syntax.
>
May I suggest some reading ?http://dirtsimple.org/2004/12/python-is-not-java.html
Well the Foo.Foo complaint is bogus:

from Foo import Foo

Sep 10 '07 #9
bg***@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.python.org/pypi/enum/>

--
\ "Remorse: Regret that one waited so long to do it." -- Henry |
`\ L. Mencken |
_o__) |
Ben Finney
Sep 11 '07 #10
TheFlyingDutchman a écrit :
On Sep 8, 9:52 am, Bruno Desthuilliers
<bdesth.quelquech...@free.quelquepart.frwrote:
>>TheFlyingDutchman a écrit :
(snip)
>>>class TestOutcomes:
PASSED = 0
FAILED = 1
ABORTED = 2
>> def ToString(outcome):
if outcome == TestOutcomes.PASSED:
return "Passed"
elif outcome == TestOutcomes.FAILED :
return "Failed"
else:
return "Aborted"
>> ToString = staticmethod(ToString)
(snip)
>>Technically correct, but totally unpythonic.


Speaking of unpythonic, I would call

ToString = staticmethod(ToString)

A Perlific syntax.
Nope, just a good ole HOF.

But nowadays, it's usually written this way:

@staticmethod
def some_static_method():
pass
>
>>May I suggest some reading ?http://dirtsimple.org/2004/12/python-is-not-java.html

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...
Sep 11 '07 #11
On Mon, 10 Sep 2007 02:28:57 -0700, bg***@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?
You should implement __str__ (or __repr__) method in your class,

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

def __str__(self):
textResultAsString="Unknown"
if testResult == TestOutcomes.PASSED:
testResultAsString = "Passed"
elif testResult == TestOutcomes.FAILED :
testResultAsString = "Failed"
else:
testResultAsString = "Aborted"
return testResultAsString

Regards,

Zara

Sep 11 '07 #12
TheFlyingDutchman <zz******@aol.comwrites:
On Sep 10, 7:55 pm, "J. Cliff Dyer" <j...@sdf.lonestar.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
Sep 11 '07 #13
Zara wrote:
On Mon, 10 Sep 2007 02:28:57 -0700, bg***@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?

You should implement __str__ (or __repr__) method in your class,

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

def __str__(self):
textResultAsString="Unknown"
if testResult == TestOutcomes.PASSED:
testResultAsString = "Passed"
elif testResult == TestOutcomes.FAILED :
testResultAsString = "Failed"
else:
testResultAsString = "Aborted"
return testResultAsString

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.ABORTED:/

Cheers,
Cliff
Sep 11 '07 #14
bg***@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
Sc***********@Acm.Org
Sep 11 '07 #15
On 2007-09-11, Steven D'Aprano <st***@REMOVE-THIS-cybersource.com.auwrote:
Perhaps Ben should have followed the usual practice of
commercial, closed- source software developers and started
counting his version numbers at one instead of zero, miss a few
releases, use randomly large increments occasionally, and ended
up with a current version number of 2.7.1 for the exact same
level of functionality.

Or he could have called it "Enum XP" (for "eXtra Programming"
perhaps) or "Enum 2007". The next minor release could be "Enum
2008", and the next major update could be called "Enum
Professional Capowie!!!".
I like the (priviledged) code names adopted by the Linux
community for special versions, e.g., Enum 2.7.1 (Flapjacks).
This would really tie the Enum-using community together, and make
messages about it much cuter.

--
Neil Cerutti
Sep 12 '07 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Suresh | last post by:
Hi, I need to add a custom ToString method on an Enum Property. The default ToString method expands the whole name. But, I want only an short associated code with the long name of the enum type....
21
by: Andreas Huber | last post by:
Hi there Spending half an hour searching through the archive I haven't found a rationale for the following behavior. using System; // note the missing Flags attribute enum Color {
9
by: Lawrence Oluyede | last post by:
I have a list of strings and i'd like to build up an enum from them... is there a way to do that? Thanks in advance. -- Lawrence "Rhymes" Oluyede http://loluyede.blogspot.com
5
by: Barry | last post by:
Hello, In VS2003, I tried using an enum and setting it into a field in a datarow. It seems as if the datatype of the field in the row determined what went into the field. If the datatype was...
6
by: giannik | last post by:
I have an Enum Structure Public Enum MyEnum EnumVal1=0 EnumVal2=1 EnumVal2=2 end enum I save in an access database this enum value as an integer (0=EnumVal1,
7
by: Harris | last post by:
Dear all, I have the following codes: ====== public enum Enum_Value { Value0 = 0, Value1 = 10,
34
by: Steven Nagy | last post by:
So I was needing some extra power from my enums and implemented the typesafe enum pattern. And it got me to thinking... why should I EVER use standard enums? There's now a nice little code...
3
by: hufaunder | last post by:
Imagine you have a charting library that can draw lines, bars, floating bars, bands, etc. Lines and bars need only one input. Floating bars and bands need two inputs. There are two approaches: ...
3
by: Ralfeus | last post by:
Hi all Oftenly I need to use enums but standard C# enums provide little bit poor possibilities. For example I'd like to restrict variables to get only values specified in enums. Also sometimes I...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.