Advertisement
Guest User

Untitled

a guest
Jul 20th, 2017
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. import typing
  2. from sys import _getframe
  3.  
  4.  
  5. class Enum(int):
  6. __slots__ = []
  7. """type: typing.FrozenSet[str]"""
  8. names2values = dict() # TODO: make it FrozenBimap
  9. """type: typing.Dict[str, int]"""
  10. values2names = dict()
  11. """type: typing.Dict[int, str]"""
  12. _counter = -1
  13.  
  14. def __new__(cls, value):
  15. cls._counter = value
  16. return int.__new__(cls, int(value))
  17.  
  18. enumcls_t = typing.Type[Enum]
  19.  
  20.  
  21. def _no_new_instances(*args):
  22. raise Exception("no new instances permitted")
  23.  
  24.  
  25. def _lock_enum_type(cls: typing.Type[Enum]):
  26. cls.__new__ = _no_new_instances
  27.  
  28.  
  29. def begin_enum(cls: typing.Type[Enum]):
  30. cls._snap_before = frozenset(_getframe(1).f_globals.keys())
  31.  
  32.  
  33. def end_enum(cls: typing.Type[Enum]):
  34. cls_globals = _getframe(1).f_globals
  35. names = frozenset(cls_globals.keys()) - cls._snap_before
  36. del cls._snap_before
  37.  
  38. cls.names2values = {name: cls_globals[name] for name in names}
  39. cls.values2names = {cls_globals[name]: name for name in names}
  40.  
  41. _lock_enum_type(cls)
  42.  
  43.  
  44. def next(cls: typing.Type[Enum]):
  45. return cls(cls._counter + 1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement