In C or VBA Enum, the value of each member may or may not be specified, otherwise it will be the value of the previous member + 1. The first member will be 0 if no value is specified.
Personally, when dealing with input files such as CSV in VBA, I often use Enum type because it is convenient to identify the field of the file. For example, it looks like the following.
Public Enum FieldID
OrderNo = 1
CustomerNo
PurchaseDate
ProductID = 10
Price
Units
Amount
End Enum
As in this example, if you have a small number of elements, you may not appreciate it, but if you define a field in a file that has dozens of columns, all members will have columns added or removed. This is convenient because you do not have to renumber it.
In Python3.6, the function to automatically value the Enum type was added, so I tried to see if it could be done in the same way.
Python added the Enum class to the standard library in version 3.4. Python Enums are well documented in the here article.
As you can see in the Enum Library Documentation (https://docs.python.org/3/library/enum.html), Python 3.6 allows Enums to be automatically priced, = auto () The expression
has been added. (Actually, ʻauto` is a class and calls its constructor.)
I tried the same thing as the VBA code above.
from enum import IntEnum, auto
class Field(IntEnum):
OrderNo = 1
CustomerNo = auto()
PurchaseDate = auto()
ProductID = 10
Price = auto()
Units = auto()
Amount = auto()
for elm in Field:
print(elm, int(elm))
The execution result is
Field.OrderNo 1
Field.CustomerNo 2
Field.PurchaseDate 3
Field.ProductID 10
Field.Price 11
Field.Units 12
Field.Amount 13
It is necessary to write ʻauto (), but it seems to increment automatically like C and VBA. However, if the first member is
= auto ()`, it will be 1 instead of 0.
However, there is a note in the library documentation that this increment is implementation dependent. To make this behavior permanent, you need to define the behavior of ʻauto ()` yourself.
The value returned by ʻauto ()can be customized with the
generate_next_value method, so create a class ʻAutoIntoEnum
that inherits ʻIntEnum and define
generate_next_value` yourself.
from enum import IntEnum, auto
class AutoIntEnum(IntEnum):
def _generate_next_value_(name, start, count, last_values):
for last_value in reversed(last_values):
try:
return last_value + 1
except TypeError:
pass
else:
return start
class Field(AutoIntEnum):
OrderNo = auto()
CustomerNo = auto()
PurchaseDate = auto()
ProductID = 10
Price = auto()
Units = auto()
Amount = auto()
for elm in Field:
print(elm, int(elm))
This is OK even if the implementation of _generate_next_value_
changes.
The contents of _generate_next_value_
are copied as they are from Code of Enum class.
Recommended Posts