Try auto to automatically price Enums in Python 3.6

C or VBA Enum

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 Enum

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 thegenerate_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

Try auto to automatically price Enums in Python 3.6
Try to calculate Trace in Python
Try logging in to qiita with Python
Try to log in to Netflix automatically using python on your PC
Try to implement Oni Maitsuji Miserable in python
Try to calculate a statistical problem in Python
3.14 π day, so try to output in Python
Automatically register function arguments to argparse in Python
Try to automatically generate Python documents with Sphinx
Try to calculate RPN in Python (for beginners)
Try gRPC in Python
Try 9 slices in Python
Try to make a Python module in C language
Try to improve your own intro quiz in Python
To flush stdout in Python
Try to understand Python self
Login to website in Python
Try LINE Notify in Python
Speech to speech in python [text to speech]
Try implementing Yubaba in Python 3
How to develop in Python
Post to Slack in Python
Try to make it using GUI and PyQt in Python
Just try to receive a webhook in ngrok and python
How to log in to AtCoder with Python and submit automatically
[Python] How to do PCA in Python
Convert markdown to PDF in Python
How to collect images in Python
Try to operate Facebook with Python
Automatically format Python code in Vim
Try implementing extension method in python
How to use SQLite in Python
Try using LevelDB in Python (plyvel)
Let's try Fizz Buzz in Python
In the python command python points to python3.8
Try PLC register access in Python
Try to put data in MongoDB
Try converting cloudmonkey CLI to python3 -1
How to use Mysql in python
How to wrap C in Python
How to use ChemSpider in Python
6 ways to string objects in Python
How to use PubChem in Python
Cython to try in the shortest
Try using Leap Motion in Python
How to handle Japanese in Python
An alternative to `pause` in Python
Try to get a list of breaking news threads in Python.
[Cloudian # 9] Try to display the metadata of the object in Python (boto3)
[Cloudian # 2] Try to display the object storage bucket in Python (boto3)
I tried to implement PLSA in Python
[Introduction to Python] How to use class in Python?
Try using the Wunderlist API in Python
Install Pyaudio to play wave in python
How to access environment variables in Python
I tried to implement permutation in Python
Method to build Python environment in Xcode 6
How to dynamically define variables in Python
Try using the Kraken API in Python
How to do R chartr () in Python
Try working with binary data in Python