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).
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.
from enum import Enum
class Hoge(Enum):
ONE = 1
TWO = 2
THREE = 3
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]
>>> 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.
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.
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