constants in Python [was: Verifiably better, validated Enum for Python]
Ethan Furman
ethan at stoneleaf.us
Wed May 24 10:56:45 EDT 2017
On 05/24/2017 07:31 AM, Steve D'Aprano wrote:
> On Wed, 24 May 2017 10:07 pm, Chris Angelico wrote:
>> On Wed, May 24, 2017 at 7:10 PM, Steve D'Aprano 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?
>>
>> 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".
> 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.
Check out the NamedConstant class from aenum [1] -- it's probably as close as
you're going to get:
>>> from aenum import NamedConstant
>>> class Konstant(NamedConstant):
... PI = 3.14159
... TAU = 2 * PI
>>> Konstant.PI
<Konstant.PI: 3.14159>
>> print(Konstant.PI)
3.14159
>>> Konstant.PI = 'apple'
Traceback (most recent call last):
...
AttributeError: cannot rebind constant <Konstant.PI>
>>> del Konstant.PI
Traceback (most recent call last):
...
AttributeError: cannot delete constant <Konstant.PI>
> 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.
But getting around a Python-code read-only property is trivial -- not pretty, but trivial.
--
~Ethan~
[1] https://pypi.python.org/pypi/aenum
More information about the Python-list
mailing list