0

Let's say I have the following Python enum class:

class FooEnum(IntEnum):
    foo = auto()
    bar = auto()
    baz = auto()

And I also have the strings "FooEnum" and "bar". Both of the strings come from HTML select values, which are limited to basic types.

Can I turn these strings directly into a FooEnum.bar?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
TheSoundDefense
  • 6,753
  • 1
  • 30
  • 42
  • 1
    "Can I turn these strings directly into a FooEnum.bar?" you can use `eval` or an equivalent, otherwise, you need to write your own parser. Or create a dictionary mapping of string to enum class, and then use `getattr` to dynamically retrieve the enum value – juanpa.arrivillaga Feb 13 '23 at 22:03
  • 3
    But this is generally major code smell – juanpa.arrivillaga Feb 13 '23 at 22:03
  • 6
    `getattr(FooEnum, "bar")` is a fairly straightforward answer for `"bar"`, but there probably shouldn't be a good reason for anyone to be giving you a type name as a string. – chepner Feb 13 '23 at 22:03
  • 1
    The string itself isn't the problem, so much as the implication that whoever provided the string is, or must be, aware of type names in your code. – chepner Feb 13 '23 at 22:07
  • @juanpa.arrivillaga the dictionary is probably the best way to go for the class name, in this case. – TheSoundDefense Feb 13 '23 at 22:08
  • 3
    Then we're just back to https://stackoverflow.com/q/1373164/3001761. – jonrsharpe Feb 13 '23 at 22:09

1 Answers1

0

The common response here suggests that if I want to get a class name from a string, I should be using another data structure like a dictionary.

from enum import IntEnum, auto

class FooEnum(IntEnum):
  foo = auto()
  bar = auto()
  baz = auto()

class SpamEnum(IntEnum):
  spam = auto()
  eggs = auto()

enumDict = {
  "FooEnum": FooEnum,
  "SpamEnum": SpamEnum
}

With the above code, enumDict["FooEnum"]["bar"] gives FooEnum.bar.

In retrospect, there is no situation I can think of where I wouldn't know all of my class names, so it's hard to imagine a dictionary not being a reasonable solution.

TheSoundDefense
  • 6,753
  • 1
  • 30
  • 42