If you will be using these aliases directly in your code (not just referenced from data structures) then an Enum
is a good way to go1:
from enum import Enum
class Alias(Enum):
bob = 12345
jon = 23456
jack = 34567
jill = 45678
steph = 89012
Then using re
would look like:
line = "hey there 12345!"
line = re.sub('\d{5}', lambda v: Alias(int(v.group()).name, line)
You could also add that behavior directly to the Alias
Enum
with a method:
@classmethod
def sub(cls, line):
return re.sub('\d{5}', lambda v: cls(int(v.group())).name, line)
and in use:
Alias.sub("hey there 12345!")
Of course, "bob"
should probably be capitalized, but who wants Alias.Bob
all over their code? Best to have the substitution text be separate from the Enum member name, a job more easily accomplished with aenum
2:
from aenum import Enum
import re
class Alias(Enum):
_init_ = 'value text'
bob = 12345, 'Bob'
jon = 23456, 'Jon'
jack = 34567, 'Jack'
jill = 45678, 'Jill'
steph = 89012, 'Steph'
@classmethod
def sub(cls, line):
return re.sub('\d{5}', lambda v: cls(int(v.group())).text, line)
Alias.sub('hey there 34567!')
1 See this answer for the standard Enum
usage.
2 Disclosure: I am the author of the Python stdlib Enum
, the enum34
backport, and the Advanced Enumeration (aenum
) library.