Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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)'
- 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
- >>>
- >>> 1 .__hash__() == hash(1)
- True
- >>> int.__hash__() == hash(int)
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- TypeError: descriptor '__hash__' of 'int' object needs an argument
- typedict = enums.copy()
- typedict.update({
- 'name': reverse,
- '__repr__': reprfun,
- '__str__': reprfun,
- })
- instance = type('Enum', (), typedict)
- return instance
- >>> x = Enum(X=1, Y=2)
- >>> x
- <class '__main__.Enum'>
- >>> x.__repr__
- <unbound method Enum.reprfun>
- >>> x()
- Enum(Y=2, X=1)
- >>> str(x())
- 'Enum(Y=2, X=1)'
- >>> repr(x())
- 'Enum(Y=2, X=1)'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement