Verifiably better, validated Enum for Python

Ian Kelly ian.g.kelly at gmail.com
Wed May 24 15:10:46 EDT 2017


On Wed, May 24, 2017 at 3:10 AM, Steve D'Aprano
<steve+python at pearwood.info> wrote:
> The page says:
>
>     venum provides an Enum that is actually just a namedtuple,

No kidding. This is the entirety of the code for it:


from collections import namedtuple


def Enum(*args, **kwargs):
    fields, values = zip(*args)
    return namedtuple(kwargs.get('name', 'Enum'), fields)(*values)


I wanted to verify that venum was better so I started reading through
the features of https://docs.python.org/3/library/enum.html to confirm
that venum also supports them. Turns out, it supports almost none of
them.

"Enumeration members have human readable string representations" - Nope.
"...while their repr has more information" - Nope.
"The type of an enumeration member is the enumeration it belongs to" - Nope.
"Enum members also have a property that contains just their item name" - Nope.
"Enumerations support iteration, in definition order" - Finally a yes,
with the caveat that iterating over the venum only results in the
values. Although one could iterate over ._fields to get the names.
"Enumeration members are hashable, so they can be used in dictionaries
and sets" - venum members are just the values, so they're hashable if
and only if the values are hashable.

Programmatic access by value - No, you'd have to iterate over the
venum to search for the value.
Programmatic access by name - Yes, by using getattr, no convenient syntax.
Aliases for duplicate values - Depends entirely upon the identity
semantics of how the values are specified. Enum(('a', 1), ('b', 1))
would create an alias in CPython, but Enum(('a', 1000000), ('b',
1000000)) would not.
@unique decorator - no support
automatic values - no support
Iteration excludes aliases - No.
__members__ attribute - Sort of, using _fields and getattr.

Enumeration members compared by identity - Likely to cause surprises
since venum members are just values.
Ordered comparisons explicitly not supported - No, venum members may
or may not be orderable.
"Equality comparisons are defined though" - Only insofar as they're
defined for the values
"Comparisons against non-enumeration values will always compare not
equal" - No such guarantee
Defining enum methods (including special methods) and properties - no support
"Subclassing an enumeration is allowed only if the enumeration does
not define any members" - venums aren't classes so they can't be
subclassed, period.
"Enumerations can be pickled and unpickled" - Only if the value supports it.

"The Enum class is callable, providing the following functional API" -
Finally, an unqualified yes!



More information about the Python-list mailing list