473,796 Members | 2,583 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

Sep 10 '07
15 3001
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
>
>>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.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

Sep 11 '07 #12
TheFlyingDutchm an <zz******@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
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.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
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.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
Sc***********@A cm.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
7350
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. For example, public enum Color { Red = 0, Blue, Green } The statement
21
4607
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
39745
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
2874
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 string, then the name of the enum item went into the field, but if the datatype was integer, then the integer value of the enum was stored. Is this expected behaviour? I couldn't find anything while searching for answers.
6
3003
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
9837
by: Harris | last post by:
Dear all, I have the following codes: ====== public enum Enum_Value { Value0 = 0, Value1 = 10,
34
11205
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 snippet that I wrote today that gives me an instant implementation of the pattern. I could easily just always use such an implementation instead of a standard enum, so I wanted to know what you experts all thought. Is there a case for standard enums?
3
3046
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: 1) One enum with all 4 types (bars, band, etc). One chart class that accepts up to 2 arrays of values. If the user choses a band but there is only one input array throw an exception. If the user passes two input arrays with different lengths throw...
3
1290
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 want to implement some type conversion from enum to some other type. Is it possible to create a new type, which would extend an enum? Thanks
0
9528
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10455
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10006
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9052
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7547
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5441
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5573
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4116
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3731
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.