[Python-Dev] Enum: subclassing? (original) (raw)

Georg Brandl g.brandl at gmx.net
Wed May 1 23:44:03 CEST 2013


Am 01.05.2013 23:19, schrieb Eli Bendersky:

It's a common pattern to do this with a base class rather than a mixin, though, and I think the rule "only allow subclassing empty enums" makes a lot of sense.

I see your point (and Antoine's example in the next email is good), but my concern is that this is a TIMTOWTDI thing, since the same can be achieved with mixins. Specifically, Antoine's example becomes: class IETFStatusCode: @classmethod def fromstatusline(cls, line): return cls(int(line.split()[0])) class HTTPStatusCode(int, IETFStatusCode, Enum): NOTFOUND = 404 class SIPStatusCode(int, IETFStatusCode, Enum): RINGING = 180

Now try it like this:

class SIPStatusCode(IETFStatusCode, int, Enum): RINGING = 180

and you'll get

Traceback (most recent call last): File "/home/gbr/devel/ref435/ref435.py", line 84, in new enum_item = obj_type.new(result, value) TypeError: object.new(SIPStatusCode) is not safe, use int.new()

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "ex.py", line 11, in class SIPStatusCode(IETFStatusCode, int, Enum): File "/home/gbr/devel/ref435/ref435.py", line 86, in new raise EnumError(*exc.args) from None TypeError: exception causes must derive from BaseException

Same thing, while keeping the stdlib API cleaner and more minimal. Cleaner because "no subclassing" is a simpler, more explicit, and easier to understand rule than "no subclassing unless base class is devoid of enumeration values". And because we can no longer say "Enum classes are final", which is a relatively familiar and understood semantic.

I fear the "you can use mixins provided you put them in the right spot in the base classes list" rule is not much simpler than the "no subclassing of enums with values" rule.

Georg



More information about the Python-Dev mailing list