1

I have a Python enum:

class E(Enum):
  A = 1
  B = 2

It is part of a public interface, people pass E.A or E.B to various functions to specify some parameter. I want to augment this enum to add a third value, C, but this value only makes sense if you also pass a couple of additional parameters, x and y. So in addition to allowing my users to pass E.A or E.B, I want them to be able to pass e.g. E.C(x=17,y=42), and have my code access the values of these parameters (here, 17 and 42).

What's the most "pythonic" way of achieving this? I'm using Python 3.7.

Ted
  • 972
  • 2
  • 11
  • 20

1 Answers1

0

There is no Pythonic way to achieve this, as you are trying to use Enum in a way other than which it was intended. Let me explain:

First, an enum with more useful names:

class Food(Enum):
    APPLE = 1
    BANANA = 2
    CARROT = 3

Each enum member (so APPLE and BANANA above) is a singleton -- there will only ever be one Food.APPLE, one Food.BANANA, and one Food.CARROT (if you add it). If you add an x and y attribute to Food.CARROT, then everywhere you use Food.CARROT you will see whatever x and y were last set to.

For example, if func1 calls func2 with Food.CARROT(17, 19), and func2 calls func3 with Food.CARROT(99, 101), then when func1 regains control it will see Food.CARROT.x == 99 and Food.CARROT.y == 101.

The way to solve this particular problem is just to add the x and y parameters to your functions, and have the functions verify them (just like you would for any other parameter that had restrictions or requirements).

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
  • Thanks for the answer! I am not fond of the approach of adding `x` and `y` parameters: I would need to do that for every single option I add to this enum that has parameters, so I would end up with massive argument lists and a lot of validation code. Isn't there a reasonable way of implementing the interface I want? I don't necessarily need the result to be subclassing `Enum` anymore. – Ted Nov 09 '21 at 11:06