Advertisement
Guest User

Untitled

a guest
Apr 16th, 2014
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. In [2]: x = Enum(X=1, Y=2)
  2.  
  3. In [3]: x
  4. Out[3]: common.utils.Enum
  5.  
  6. In [4]: str(x)
  7. Out[4]: "<class 'common.utils.Enum'>"
  8.  
  9. In [5]: x.__repr__
  10. Out[5]: <bound method type.reprfun of <class 'common.utils.Enum'>>
  11.  
  12. In [6]: x.__repr__()
  13. Out[6]: 'Enum(Y=2, X=1)'
  14.  
  15. def Enum(*args, **kwargs):
  16. enums = dict(zip(args, range(len(args))), **kwargs)
  17. def reprfun(self):
  18. res = 'Enum(' +
  19. ', '.join(map(lambda x: '{}={}'.format(x[0],x[1]), enums.items())) +
  20. ')'
  21. return res
  22.  
  23. reverse = dict((value, name) for name, value in enums.items())
  24. typedict = enums.copy()
  25. typedict['name'] = reverse
  26. instance = type('Enum', (), typedict)
  27. instance.__repr__ = types.MethodType(reprfun, instance)
  28. instance.__str__ = types.MethodType(reprfun, instance)
  29. return instance
  30.  
  31. >>>
  32. >>> 1 .__hash__() == hash(1)
  33. True
  34. >>> int.__hash__() == hash(int)
  35. Traceback (most recent call last):
  36. File "<stdin>", line 1, in <module>
  37. TypeError: descriptor '__hash__' of 'int' object needs an argument
  38.  
  39. typedict = enums.copy()
  40. typedict.update({
  41. 'name': reverse,
  42. '__repr__': reprfun,
  43. '__str__': reprfun,
  44. })
  45.  
  46. instance = type('Enum', (), typedict)
  47. return instance
  48.  
  49. >>> x = Enum(X=1, Y=2)
  50. >>> x
  51. <class '__main__.Enum'>
  52. >>> x.__repr__
  53. <unbound method Enum.reprfun>
  54. >>> x()
  55. Enum(Y=2, X=1)
  56. >>> str(x())
  57. 'Enum(Y=2, X=1)'
  58. >>> repr(x())
  59. 'Enum(Y=2, X=1)'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement