Verifiably better, validated Enum for Python

Steve D'Aprano steve+python at pearwood.info
Wed May 24 10:31:17 EDT 2017


On Wed, 24 May 2017 10:07 pm, Chris Angelico wrote:

> On Wed, May 24, 2017 at 7:10 PM, Steve D'Aprano
> <steve+python at pearwood.info> wrote:
>> 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)
> 
> I'm sure it could be done. But would it really benefit anyone
> anything? Java has "final" classes, which can't be subclassed; and I
> haven't heard many people saying "I wish you would declare more of
> your classes final" or "I wish Python let you declare a class as
> final".

I've wanted that from time to time. Never quite enough to make my own
metaclass to get it, or enough to write a C extension, but if the
functionality existed, I would have used it.

Same as if Python supported constants (names that can only be assigned to
once). Again, the pain of building a custom "constant-like" solution is
greater than the benefit, so I've done without.

But if Python did support these things, maybe the compiler could make a few
optimizations, or maybe we could write a few less unit tests, or catch a
few bugs a little earlier... or not.


It's just a different way at looking at minimalism. Guido says, the language
should be as small as possible. If you don't want to assign to a name, then
just don't assign to it. No need to build support for constants into the
language when you can trust the developer to Don't Do That.

(But note that Python does support read-only attributes, a related concept.)

While other language designers take on minimalism is that the entity in
question should support as few things as possible. If you have a name that
you don't want to ever be rebound to a different value, then the language
shouldn't support rebinding that name, since you can't trust the developer
to Don't Do That.

Neither view is entirely right or wrong, which is why there will always be
arguments over it. But I'll note that Python has supported read-only
properties for, oh, a decade or more, and do I hear people complaining
about how much libraries and applications over-use and abuse properties?
Not very often.




-- 
Steve
Emoji: a small, fuzzy, indistinct picture used to replace a clear and
perfectly comprehensible word.




More information about the Python-list mailing list