0

I have an Enum class in python. somthing like this.

class MyEnum(Enum):
    attribute1 = "alpha/path/to/data1/"
    attribute2 = "alpha/path/to/data2/"

in this class, "alpha" is hard-coded. but now I have a variable called ENVIRONMENT that its value is "alpha" or "beta" I want to use this variable in MyEnum attributes. how can I do this?

I searched and I found DynamicClassAttribute class. but I didn't know how to use that

  • Does this answer your question? [What is a DynamicClassAttribute and how do I use it?](https://stackoverflow.com/questions/36040996/what-is-a-dynamicclassattribute-and-how-do-i-use-it) – Yevhen Kuzmovych Jun 14 '23 at 13:25
  • 2
    Is `ENVIRONMENT` intended to be constant at runtime, or is it expected to change? – 0x5453 Jun 14 '23 at 13:41

2 Answers2

0

I found the answer. I overrode the value method of the Enum class and inside that I changed the value.

class MyEnum(Enum):
    attribute1 = "{}/path/to/data1/"
    attribute2 = "{}/path/to/data2/"

    @DynamicClassAttribute
    def value(self):
        return self._value_.format(ENVIRONMENT)
-2

try this ruff notion

from enum import Enum, DynamicClassAttribute

ENVIRONMENT = "alpha"

class MyEnum(Enum):
    @DynamicClassAttribute
    def attribute1(cls):
        return f"{ENVIRONMENT}/path/to/data1/"

    @DynamicClassAttribute
    def attribute2(cls):
        return f"{ENVIRONMENT}/path/to/data2/"

if you use the @DynamicClassAttribute decorator, you can define methods in your Enum class that will be called dynamically to assign values to the attributes. These methods will receive the class (i.e., cls) as a parameter, and you can access the ENVIRONMENT variable within these methods.

You will get the values based on the ENVIRONMENT variable. For example:

print(MyEnum.attribute1.value)  # Output: alpha/path/to/data1/
print(MyEnum.attribute2.value)  # Output: alpha/path/to/data2/
Nilanj
  • 101
  • 12
  • Try first and than give down points – Nilanj Jun 14 '23 at 13:43
  • This doesn't work at all. `DynamicClassAttribute` doesn't work like what you describe (plus you're not supposed to import it from `enum` anyway - it's something `enum` imports from `types` for its own internal use, not part of `enum`'s public API). – user2357112 Jun 14 '23 at 13:43