Consider the following enum class:
from enum import Enum
class Namespace:
class StockAPI(Enum):
ITEMS = "{url}/items"
INVENTORY = "{url}/inventory"
class CustomerAPI(Enum):
USERS = "{url}/users"
PURCHASES = "{url}/purchases"
def __init__(self, url):
self.url = url
I am trying to make url a dynamic value for each enum class.
What can I do here so that I can call some enum class in one of the following ways:
Namespace.StockAPI.ITEMS.value would return http://localhost/items?Namespace(url="http://localhost").StockAPI.ITEMS.value would also return http://localhost/itemsIs this possible to do without doing variable interpolation each time I access each enum property? Could factory pattern be of any help here?
I did it the following way, while keeping the inner enum classes:
from enum import Enum
class Namespace:
class StockAPI(Enum):
ITEMS = "{url}/items"
INVENTORY = "{url}/inventory"
class CustomerAPI(Enum):
USERS = "{url}/users"
PURCHASES = "{url}/purchases"
def __init__(self, url: str):
attrs = (getattr(self, attr) for attr in dir(self))
enums = (a for a in attrs if isinstance(a, type) and issubclass(a, Enum))
for enum in enums:
kv = {e.name: e.value.format(url=url) for e in enum}
setattr(self, enum.__name__, Enum(enum.__name__, kv))
print(Namespace(url="http://test.com").StockAPI.ITEMS.value)
# http://test.com/items
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With