Verifiably better, validated Enum for Python
Steve D'Aprano
steve+python at pearwood.info
Wed May 24 05:10:07 EDT 2017
On Wed, 24 May 2017 01:47 pm, breamoreboy at gmail.com wrote:
> Well that's what is says here https://github.com/ofek/venum so it must be
> true. Please move over Ethan, your time is up :-)
The page says:
venum provides an Enum that is actually just a namedtuple, but
easier to create. This means an Enum can be created during
program execution and members are truly immutable (can't
dynamically add new ones). Also, this saves a bit of space
over the stdlib's Enum.
(1) Std lib enums are created during program execution too.
(2) Being namedtuples is a negative, not a positive.
(3) Members being immutable may, or may not, be a good thing, depending on
the application.
(4) If it is true that venum uses less space (memory? disk space?) than
enum, that would be a positive.
The example given is:
>>> from venum import Enum
>>> ContentTypes = Enum(
... ('JSON', 'application/json; charset=utf-8'),
... ('HTML', 'text/html; charset=utf-8'),
... ('JS', 'text/javascript; charset=utf-8'),
... ('XML', 'application/xml'),
... ('TEXT', 'text/plain; charset=utf-8'),
... ('JPEG', 'image/jpeg'),
... ('PNG', 'image/png'),
... ('YAML', 'application/x-yaml'),
... name='ContentTypes'
... )
but I'm not convinced that's "verifiably better" than:
from enum import Enum
class ContentTypes(Enum):
JSON = 'application/json; charset=utf-8'
HTML = 'text/html; charset=utf-8'
JS = 'text/javascript; charset=utf-8'
XML = 'application/xml'
TEXT = 'text/plain; charset=utf-8'
JPEG = 'image/jpeg'
PNG = 'image/png'
YAML = 'application/x-yaml'
Although I wonder:
- maybe the enumeration (the class ContentTypes) could have a nicer repr
than
<enum 'ContentTypes'>
- maybe you could add functionality to freeze the enumeration so that new
members cannot be added?
class ContentTypes(Enum, frozen=True)
class ContentTypes(FrozenEnum)
--
Steve
Emoji: a small, fuzzy, indistinct picture used to replace a clear and
perfectly comprehensible word.
More information about the Python-list
mailing list