I am implementing a model aligned with a specification that states a particular value must either be [one of the strings] “foo” or “bar”. To that end I thought I’d see if Python offers enumeration types, and apparently it does. I picked StrEnum
of the enum
module where I create the type as follows:
Foobar = StrEnum('Foobar', ('foo', 'bar'))
This works to my satisfaction except for the fact I depend on the representation of Foobar
objects to be “reversible” to Python, and I’d rather not muck about with my own __repr__
implementations or serialization routines (including “pickling”), if I can avoid — in particular the latter kind.
I have objects of the type created above, referenced by all manner of other objects, which are routinely “serialized” with repr
into text I then evaluate as Python expression text, as validation tests I do.
I therefore rely on __repr__
for the type above return Foobar('foo')
so that evaluating the text as Python expression (with e.g. eval
) effectively restores the corresponding object. I am well aware I could do pickling or some facility designed for serialization, but I don’t want to because, frankly, repr
has supported my use case perfectly, save for the seemingly annoying fact that repr
for specifically StrEnum
(and probably Enum
) prefers to return text like "<Foobar.foo: 'foo'>"
, which isn’t conforming to any particular format I know of, except apparently one chosen by StrEnum
(as implemented by Enum
, probably), and is certainly not a valid Python expression string. So it’s a no-go for me.
Is there a known good reasons designers of enumeration types that are part of Python (3.11), decided to represent enumeration values with said “free-form” format, when Python itself recommends repr
offers a “pythonic”-formatted value 1:
If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment)
If there isn’t a good reason behind the choice, I guess I can attach a __repr__
of my making to the class, thus “fixing” it for my needs. If there is [a good reason], I should want to think on it, before I decide to [still] attach a __repr__
of my own, again, although I have mulled over writing a distinct repr
instead but that wouldn’t be very Pythonic unless I make it rely on e.g. __pythonic_repr__
which I’d either then have to attach to every object I conceivably turn to text and back, or something to similar effect.