PEP 354: Enumerations in Python
Ben Finney
bignose+hates-spam at benfinney.id.au
Tue Feb 28 20:15:13 EST 2006
Roy Smith <roy at panix.com> writes:
> A few random questions:
>
> a = enum ('foo', 'bar', 'baz')
> b = enum ('foo', 'bar', 'baz')
Two separate enumerations are created, and bound to the names 'a' and
'b'. Each one has three unique member values, distinct from any
others.
> what's the value of the following:
>
> a == b
False
(the enumeration objects are not the same, and don't contain the same
values)
> a is b
False
(the enumeration objects are not the same)
> a.foo == b.foo
False
(the comparison function returns NotImplemented when comparing values
from different enumerations. The Python interpreter [thanks Alex
Martelli :-)] will evaluate the comparison as False)
> a.foo is b.foo
False
(the members of each enumeration are created as separate values)
> len (a)
3
(enumerations are iterable)
> str (a)
Not defined in the current specification. Suggestions?
> repr (a)
Not defined in the current specification. Suggestions?
> hash (a)
-1210774164 # or some other hash value
(falls back on the 'object' hash function)
> type (a)
<type 'enum'> # if included in the language
<class 'collections.enum'> # if in the stdlib
> Can you make an enum from a sequence?
The current specification is for an enum constructor to accept its
member names as separate arguments, to allow for the expected common
use case::
foo = enum('bar', 'baz', 'bucket')
> syllables = ['foo', 'bar', 'baz']
> c = enum (syllables)
Can be done with::
c = enum(*syllables)
> You imply that it works from "An enumerated type is created from a
> sequence of arguments to the type's constructor", but I suspect
> that's not what you intended.
That's what I intended; a sequence of arguments. Is there a better way
to refer to the positional arguments collectively?
> BTW, I think this is a great proposal; enums are a badly needed part
> of the language.
Thanks. I hope we can arrive at a consensus view of how enums should
work in Python.
> There's been a number of threads recently where people called
> regex methods with flags (i.e. re.I) when integers were expected, with
> bizarre results. Making the flags into an enum would solve the problem
> while retaining backwards compatibility.
Yes, this is a prime use case for enums. I tried to cover this in the
"Motivation"::
Other examples include error status values and states
within a defined process.
Can anyone think of a better way to express this, without necessarily
referring to any specific set of flags or states or codes or whatever?
--
\ "To be yourself in a world that is constantly trying to make |
`\ you something else is the greatest accomplishment." -- Ralph |
_o__) Waldo Emerson |
Ben Finney
More information about the Python-list
mailing list