Augment a Python enum with a value taking parameters

688 Views Asked by At

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.

1

There are 1 best solutions below

1
On

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).