I'm rolling my own Enum
class for python and I'm having trouble getting __str__
and __repr__
to work correctly, what am I doing wrong?
In [2]: x = Enum(X=1, Y=2)
In [3]: x
Out[3]: common.utils.Enum
In [4]: str(x)
Out[4]: "<class 'common.utils.Enum'>"
In [5]: x.__repr__
Out[5]: <bound method type.reprfun of <class 'common.utils.Enum'>>
In [6]: x.__repr__()
Out[6]: 'Enum(Y=2, X=1)'
The code itself:
def Enum(*args, **kwargs):
enums = dict(zip(args, range(len(args))), **kwargs)
def reprfun(self):
res = 'Enum(' +\
', '.join(map(lambda x: '{}={}'.format(x[0],x[1]), enums.items())) +\
')'
return res
reverse = dict((value, name) for name, value in enums.items())
typedict = enums.copy()
typedict['name'] = reverse
instance = type('Enum', (), typedict)
instance.__repr__ = types.MethodType(reprfun, instance)
instance.__str__ = types.MethodType(reprfun, instance)
return instance