Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend Python Enum?

What is best practice for extending Enum type in Python 3.4 and is there even a possibility for do this?

For example:

from enum import Enum  class EventStatus(Enum):    success = 0    failure = 1  class BookingStatus(EventStatus):    duplicate = 2    unknown = 3  Traceback (most recent call last): ... TypeError: Cannot extend enumerations 

Currently there is no possible way to create a base enum class with members and use it in other enum classes (like in the example above). Is there any other way to implement inheritance for Python enums?

like image 402
falek.marcin Avatar asked Nov 12 '15 19:11

falek.marcin


People also ask

Can you extend an enum?

No, we cannot extend an enum in Java. Java enums can extend java. lang. Enum class implicitly, so enum types cannot extend another class.

What is Auto () in Python?

With the help of enum. auto() method, we can get the assigned integer value automatically by just using enum. auto() method. Syntax : enum.auto() Automatically assign the integer value to the values of enum class attributes.

Can Python enum have methods?

Customize Python enum classes Python enumerations are classes. It means that you can add methods to them, or implement the dunder methods to customize their behaviors.


2 Answers

Subclassing an enumeration is allowed only if the enumeration does not define any members.

Allowing subclassing of enums that define members would lead to a violation of some important invariants of types and instances.

https://docs.python.org/3/library/enum.html#restricted-enum-subclassing

So no, it's not directly possible.

like image 60
GingerPlusPlus Avatar answered Oct 11 '22 10:10

GingerPlusPlus


While uncommon, it is sometimes useful to create an enum from many modules. The aenum1 library supports this with an extend_enum function:

from aenum import Enum, extend_enum  class Index(Enum):     DeviceType    = 0x1000     ErrorRegister = 0x1001  for name, value in (         ('ControlWord', 0x6040),         ('StatusWord', 0x6041),         ('OperationMode', 0x6060),         ):     extend_enum(Index, name, value)  assert len(Index) == 5 assert list(Index) == [Index.DeviceType, Index.ErrorRegister, Index.ControlWord, Index.StatusWord, Index.OperationMode] assert Index.DeviceType.value == 0x1000 assert Index.StatusWord.value == 0x6041 

1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.

like image 40
Ethan Furman Avatar answered Oct 11 '22 11:10

Ethan Furman