Is there a way to create an Enum
in Python that calculates the value each time the Enum
attribute is accessed? Specifically, I'm trying to create an Enum
class that stores values like TODAY
, TOMORROW
, etc. for a web app (in Django) that runs for many days and I want the value recalculated each time it's accessed in case the day changes. So, say, the app is launched on March 1, if the app makes the check for TODAY
on March 3, it will return March 3 and not March 1 which is what it would be initialized for.
from enum import Enum
import datetime
class MyEnum(Enum):
TODAY = datetime.datetime.now()
TOMORROW = datetime.datetime.now() + datetime.timedelta(days=1)
You can do this by programming a descriptor, like:
from datetime import datetime, timedelta
from enum import Enum
class DtDiff:
def __init__(self, delta=timedelta()):
self.delta = delta
def __get__(self, obj, objtype=None):
return datetime.now() + self.delta
class MyEnum(Enum):
TODAY = DtDiff()
TOMORROW = DtDiff(timedelta(days=1))
But in this case this will even nullify most functionalities of the Enum, hence it is likely not a good idea.
Probably a better way is just define a function on the Enum
, like:
from datetime import datetime, timedelta
from enum import Enum
class MyEnum(Enum):
TODAY = timedelta(0)
TOMORROW = timedelta(days=1)
@property
def timestamp(self):
return datetime.now() + self.value
You then can just get the timestamp with:
>>> MyEnum.TODAY.timestamp
datetime.datetime(2023, 6, 24, 19, 32, 41, 854253)
which looks like a minimal amount of work to get the timestamp for an enum choice.