Suppose I have a class which extends Enum
, named foo; However, instead of using integers for each item, I use strings
from enum import Enum
class foo (Enum):
foo = "Hello"
bar = ", "
foobar = "world"
barfoo = "!"
When compiling, the system will throw no errors, and happily treat this class as a normal enum. As per why anyone would want to do this, it's very useful if you want to link each name to a data structure, like a dict. Take this as an example:
from enum import Enum
class foo (Enum):
foo = {"text" : "Hello", "meaning" : "hello"}
bar = {"text" : ", ", "meaning" : "comma"}
foobar = {"text" : "world", "meaning" : "world"}
barfoo = {"text" : "!", "meaning" : "exclamation"}
Well, maze, why not just use a normal class then?
Well, its very useful to be able to store this information as an enum, for quick comparison of type. For example, x = {"name" : "foo", "type" : foo.foo}
can be easily checked for type with if x[type] is foo.foo
.
Is this a "bad practice"? By that, I mean:
- Is this an intended use of
Enum
? - If I took out the
(Enum)
fromclass foo (Enum):
, would there be any efficiency difference when comparing? - Is there a better way to do what I am wanting to do?