How to apply a method to all values in Enum class?
Question:
I have some Enum
s which may or may not have clashing names but are in different modules, so I want to apply some sort of prefix / suffix lambda to make them unique without having to manually specify it for each value. How can I alter my Enum
class definitions to do something like the following? Thanks!
# foo.py
class Ids(Enum):
# define some accessor lambda or dunder override?
some_id = auto()
# many more...
# bar.py
class Ids(Enum):
# define some accessor lambda or dunder override?
some_id = auto()
# many more...
# baz.py
from foo import Ids as FooIds
from bar import Ids as BarIds
print(FooIds.some_id) # foo-some_id
print(BarIds.some_id) # bar-some_id
Answers:
You can implement auto()
however you want (note, the implementation may be different depending on your Python version, I’m on 3.9.15
here):
from enum import auto, Enum
# foo.py
class Ids(Enum):
def _generate_next_value_(name, start, count, last_values):
return f"foo-{count+1}"
ID1 = auto()
ID2 = auto()
# bar.py
class Ids(Enum):
def _generate_next_value_(name, start, count, last_values):
return f"bar-{count+1}"
ID1 = auto()
ID2 = auto()
output (both defined in same iPython session as FooIds
and BarIds
, respectively):
In [2]: FooIds.ID1
Out[2]: <FooIds.ID1: 'foo-1'>
In [3]: BarIds.ID1
Out[3]: <BarIds.ID1: 'bar-1'>
Is there some particular reason you’re using Enum
here though? Why do you have two separate Enums doing almost the same thing?
I have some Enum
s which may or may not have clashing names but are in different modules, so I want to apply some sort of prefix / suffix lambda to make them unique without having to manually specify it for each value. How can I alter my Enum
class definitions to do something like the following? Thanks!
# foo.py
class Ids(Enum):
# define some accessor lambda or dunder override?
some_id = auto()
# many more...
# bar.py
class Ids(Enum):
# define some accessor lambda or dunder override?
some_id = auto()
# many more...
# baz.py
from foo import Ids as FooIds
from bar import Ids as BarIds
print(FooIds.some_id) # foo-some_id
print(BarIds.some_id) # bar-some_id
You can implement auto()
however you want (note, the implementation may be different depending on your Python version, I’m on 3.9.15
here):
from enum import auto, Enum
# foo.py
class Ids(Enum):
def _generate_next_value_(name, start, count, last_values):
return f"foo-{count+1}"
ID1 = auto()
ID2 = auto()
# bar.py
class Ids(Enum):
def _generate_next_value_(name, start, count, last_values):
return f"bar-{count+1}"
ID1 = auto()
ID2 = auto()
output (both defined in same iPython session as FooIds
and BarIds
, respectively):
In [2]: FooIds.ID1
Out[2]: <FooIds.ID1: 'foo-1'>
In [3]: BarIds.ID1
Out[3]: <BarIds.ID1: 'bar-1'>
Is there some particular reason you’re using Enum
here though? Why do you have two separate Enums doing almost the same thing?