Comparing Python enums to Java, was: How much sanity checking is required for function inputs?

Chris Angelico rosuav at gmail.com
Sun Apr 24 14:27:43 EDT 2016


On Mon, Apr 25, 2016 at 4:12 AM, Ethan Furman <ethan at stoneleaf.us> wrote:
> On 04/24/2016 09:47 AM, Chris Angelico wrote:
>
>> I would normally expect enumerated values to be immutable and
>> hashable, but that isn't actually required by the code AIUI. Under
>> what circumstances is it useful to have mutable enum values?
>
>
> Values can be anything.  The names are immutable and hashable.

I know they *can* be, because I looked in the docs; but does it make
sense to a human? Sure, we can legally do this:

>>> class Color(Enum):
...     red = 1
...     green = 2
...     blue = 3
...     break_me = [0xA0, 0xF0, 0xC0]
...
>>> Color([0xA0, 0xF0, 0xC0])
<Color.break_me: [160, 240, 192]>
>>> Color([0xA0, 0xF0, 0xC0]).value.append(1)
>>> Color([0xA0, 0xF0, 0xC0]).value.append(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/enum.py", line 241, in __call__
    return cls.__new__(cls, value)
  File "/usr/local/lib/python3.6/enum.py", line 476, in __new__
    raise ValueError("%r is not a valid %s" % (value, cls.__name__))
ValueError: [160, 240, 192] is not a valid Color

but I don't think it's a good thing to ever intentionally do. It's
fine for the Enum class to not enforce it (it means you can use
arbitrary objects as values, and that's fine), but if you actually do
this, then <insert WAT image>.

At some point, we're moving beyond the concept of "enumeration" and
settling on "types.SimpleNamespace".

ChrisA



More information about the Python-list mailing list