[Python] How to get a value with a key other than value with Enum

How to get a value with a key other than value with Enum

Introduction

Many programming languages have an Enum. It's in Python as well. To get a member, you can get each value as a key, but you cannot get any other value as a key. I will introduce it because it was possible by extending the normal Enum.

Normal Enum confirmation

First, let's check how to use Enum normally.

>>> from enum import Enum
>>>
>>> class Color(Enum):
...     RED = 1
...     GREEN = 2
...     BLUE = 3

#If you declare an Enum as above
#You can access each member by using a value such as 1 or 2 as a key.

>>> color = Color(1)
>>> print(color)
Color.RED

#Of course you can also access it directly
>>> print(Color.RED)
Color.RED
>>> print(color == Color.RED)
True

Thing you want to do

You could access Color.RED withColor (1), but if you can access withColor ('red')andColor ('red')for example, the possibilities of ʻEnum` will expand.

>>> from enum import Enum
>>>
>>> class Color(Enum):
...     RED = 1
...     GREEN = 2
...     BLUE = 3

#Of course I get an error when I try to access as below
>>> color = Color('red')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python3.6/enum.py", line 293, in __call__
    return cls.__new__(cls, value)
  File "/usr/local/lib/python3.6/enum.py", line 535, in __new__
    return cls._missing_(value)
  File "/usr/local/lib/python3.6/enum.py", line 548, in _missing_
    raise ValueError("%r is not a valid %s" % (value, cls.__name__))
ValueError: 'red' is not a valid Color

>>> color = Color('Red')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python3.6/enum.py", line 293, in __call__
    return cls.__new__(cls, value)
  File "/usr/local/lib/python3.6/enum.py", line 535, in __new__
    return cls._missing_(value)
  File "/usr/local/lib/python3.6/enum.py", line 548, in _missing_
    raise ValueError("%r is not a valid %s" % (value, cls.__name__))
ValueError: 'Red' is not a valid Color

Implementation

Now let's check the implementation of Enum that extends key.

#At the time of declaration as follows`_value2member_map_`To update
>>> from enum import Enum
>>>
>>> class Color(Enum):
...     def __new__(cls, value, en, ja):
...         obj = object.__new__(cls)
...         obj._value_ = value
...         cls._value2member_map_.update({en: obj, ja: obj})
...         return obj
...     RED = (1, 'red', 'Red')
...     GREEN = (2, 'green', 'Green')
...     BLUE = (3, 'blue', 'Blue')

#With this as before'red'Or'Red'When you access with
>>> color = Color('red')
>>> print(color)
Color.RED

>>> red = Color('Red')
>>> print(red)
Color.RED

Finally

If you overdo it, the key may be worn, but I think it's worth knowing. It seems that it can be used with int type in DB and str type in API.

Recommended Posts

[Python] How to get a value with a key other than value with Enum
How to get started with Python
How to extract other than a specific index with Numpy
How to get the last (last) value in a list in Python
How to get a stacktrace in python
How to read a CSV file with Python 2/3
A layman wants to get started with Python
How to get a value from a parameter store in lambda (using python)
How to convert / restore a string with [] in python
[Python] How to draw a line graph with Matplotlib
How to get a logged-in user with Django's forms.py
How to get more than 1000 data with SQLAlchemy + MySQLdb
How to get mouse wheel verdict with Python curses
[Python] How to create a 2D histogram with Matplotlib
[Python] How to draw a scatter plot with Matplotlib
How to get a list of files in the same directory with python
[Introduction to Python] How to get the index of data with a for statement
Get the value of a specific key in a list from the dictionary type in the list with Python
How to install NPI + send a message to line with python
How to convert an array to a dictionary with Python [Application]
I tried "How to get a method decorated in Python"
How to check if a value exists in an enum
How to build a python2.7 series development environment with Vagrant
How to get into the python development environment with Vagrant
How to use a file other than .fabricrc as a configuration file
[Introduction to Python] How to get data with the listdir function
How to write a Python class
Python: How to use async with
How to get the Python version
How to get started with Scrapy
How to get started with Django
How to use FTP with Python
How to calculate date with python
Run the program without building a Python environment! !! (How to get started with Google Colaboratory)
Get the value of a specific key up to the specified index in the dictionary list in Python
How to batch start a python program created with Jupyter notebook
[Python 3.8 ~] How to define a recursive function smartly with a lambda expression
[Python] A memo that I tried to get started with asyncio
How to get a string from a command line argument in python
[Python] How to get & change rows / columns / values from a table.
How to create a heatmap with an arbitrary domain in Python
Here's a brief summary of how to get started with Django
[ROS2] How to play a bag file with python format launch
How to send a request to the DMM (FANZA) API with python
How to get parent id with sqlalchemy
How to add a package with PyCharm
[Python] How to make a class iterable
[Python] How to convert a 2D list to a 1D list
How to work with BigQuery in Python
[Python] How to invert a character string
How to deal with enum compatibility errors
How to do portmanteau test with python
How to display python Japanese with lolipop
How to enter Japanese with Python curses
[Python] How to deal with module errors
How Python beginners get started with Python with Progete
How to get started with laravel (Linux)
How to run a Maya Python script
How to install python3 with docker centos
[Python] What is a formal argument? How to set the initial value
[Yahoo! Weather Replacement Version] How to get weather information with LINE Notify + Python