[PYTHON] How to check if a value exists in an enum

You want to use a constant when you want to have a value for a specific thing. When dealing with constants in Python, I personally think it's better to use ʻEnum` (enumeration type).

Isn't Python constant in the first place?

That's right. There is no strict constant, as any value can be overwritten depending on how you do it. But the official document says so.

Enumeration notation

from enum import Enum
class Hoge(Enum):
    ONE = 1
    TWO = 2
    THREE = 3

Enums and loops

Since the enumeration type is a set of identifiers, I think there are few cases where the value itself given to the identifier is meaningful. If it is a list type, it can be easily output with a for statement, but if it is an enumeration type, it requires some ingenuity in writing.

List type


>>> lst = [1, 2, 3]
>>> [l for l in lst]
[1, 2, 3]

Enum


>>> from enum import Enum
>>> class Hoge(Enum):
...     ONE = 1
...     TWO = 2
...     THREE = 3
...
>>> [v.value for n, v in Hoge.__members__.items()]
[1, 2, 3]

I think I can write if I come here

>>> from enum import Enum
>>> class Hoge(Enum):
...     ONE = 1
...     TWO = 2
...     THREE = 3
...
>>> [v.value for n, v in Hoge.__members__.items()]
[1, 2, 3]
>>> 1 in [v.value for n, v in Hoge.__members__.items()]
True

It's done. I don't know where to use it.

bonus

What's inside the enumerated __members__?

>>> Hoge.__members__
mappingproxy({
    'ONE': <Hoge.ONE: 1>,
    'TWO': <Hoge.TWO: 2>,
    'THREE': <Hoge.THREE: 3>
})

What is MappingProxyType? According to the official documentation

Read-only mapping proxy. Provides a dynamic view of mapping entries. This means that if the mapping changes, the view will reflect these changes.

I see(?) There is ʻitems ()` in this proxy. It looks like a dictionary when you take a quick look.

Postscript

I was told that there is a simpler way of writing than @shiracamus.

>>> 1 in [e.value for e in Hoge]
True

Or

>>> any(e.value == 1 for e in Hoge)
True

It seems that you can write. Thank you! !! The first one is the level of why I didn't notice ...

I can get advice by writing an article, so I thought that output is important.

Recommended Posts

How to check if a value exists in an enum
[Python] How to write an if statement in one sentence.
How to use any or all to check if it is in a dictionary (Hash)
How to get the last (last) value in a list in Python
How to check in Python if one of the elements of a list is in another list
How to find out if there is an arbitrary value in "somewhere" of pandas DataFrame
How to make a string into an array or an array into a string in Python
How to check the memory size of a variable in Python
How to create a heatmap with an arbitrary domain in Python
How to check the memory size of a dictionary in Python
[Python] How to get a value with a key other than value with Enum
Check if you can connect to a TCP port in Python
How to determine if a shell script was started in bash
Check if the URL exists in Python
How to check opencv version in python
How to clear tuples in a list (Python)
How to embed a variable in a python string
"Cython" tutorial to make Python explosive: How to parse an Enum class defined in C ++ code into a Python Enum.
How to create a JSON file in Python
How to get help in an interactive shell
How to implement a gradient picker in Houdini
How to check / extract files in RPM package
How to notify a Discord channel in Python
[Python] How to draw a histogram in Matplotlib
How to create a Rest Api in Django
How to write a named tuple document in 2020
How to count numbers in a specific range
How to read a file in a different directory
How to Mock a Public function in Pytest
How to mention a user group in slack notification, how to check the id of the user group
[Pandas] How to check duplicates and delete duplicates in a table (equivalent to deleting duplicates in Excel)
Check if the string is a number in python
How to retrieve the nth largest value in Python
How to convert / restore a string with [] in python
[Python] How to expand variables in a character string
A memorandum on how to use keras.preprocessing.image in Keras
How to use the exists clause in Django's queryset
How to make an interactive CLI tool in Golang
How to turn a .py file into an .exe file
What to do if a UnicodeDecodeError occurs in pip
How to create an image uploader in Bottle (Python)
How to deploy a Go application to an ECS instance
How to execute a command using subprocess in Python
How to reference static files in a Django project
[Linux] How to put your IP in a variable
How to convert an array to a dictionary with Python [Application]
How to import NoteBook as a module in Jupyter (IPython)
How to output a document in pdf format with Sphinx
How to swap elements in an array in Python, and how to reverse an array.
A story about how to specify a relative path in python.
How to use the __call__ method in a Python class
How to call a function
How to check ORM behavior in one file with django
How to create an instance of a particular class from dict using __new__ () in python
What to do if pip gives a DistributionError in Homebrew
How to import a file anywhere you like in Python
How to generate a public key from an SSH private key
How to make a Python package (written for an intern)
How to manipulate the DOM in an iframe with Selenium
A note on how to load a virtual environment in PyCharm
What to do if a 0xC0000005 error occurs in tf.train.start_queue_runners ()