enum.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
  2. # Copyright (C) 2003-2017 Nominum, Inc.
  3. #
  4. # Permission to use, copy, modify, and distribute this software and its
  5. # documentation for any purpose with or without fee is hereby granted,
  6. # provided that the above copyright notice and this permission notice
  7. # appear in all copies.
  8. #
  9. # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
  10. # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
  12. # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  15. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. import enum
  17. from typing import Type, TypeVar, Union
  18. TIntEnum = TypeVar("TIntEnum", bound="IntEnum")
  19. class IntEnum(enum.IntEnum):
  20. @classmethod
  21. def _missing_(cls, value):
  22. cls._check_value(value)
  23. val = int.__new__(cls, value)
  24. val._name_ = cls._extra_to_text(value, None) or f"{cls._prefix()}{value}"
  25. val._value_ = value
  26. return val
  27. @classmethod
  28. def _check_value(cls, value):
  29. max = cls._maximum()
  30. if not isinstance(value, int):
  31. raise TypeError
  32. if value < 0 or value > max:
  33. name = cls._short_name()
  34. raise ValueError(f"{name} must be an int between >= 0 and <= {max}")
  35. @classmethod
  36. def from_text(cls: Type[TIntEnum], text: str) -> TIntEnum:
  37. text = text.upper()
  38. try:
  39. return cls[text]
  40. except KeyError:
  41. pass
  42. value = cls._extra_from_text(text)
  43. if value:
  44. return value
  45. prefix = cls._prefix()
  46. if text.startswith(prefix) and text[len(prefix) :].isdigit():
  47. value = int(text[len(prefix) :])
  48. cls._check_value(value)
  49. try:
  50. return cls(value)
  51. except ValueError:
  52. return value
  53. raise cls._unknown_exception_class()
  54. @classmethod
  55. def to_text(cls: Type[TIntEnum], value: int) -> str:
  56. cls._check_value(value)
  57. try:
  58. text = cls(value).name
  59. except ValueError:
  60. text = None
  61. text = cls._extra_to_text(value, text)
  62. if text is None:
  63. text = f"{cls._prefix()}{value}"
  64. return text
  65. @classmethod
  66. def make(cls: Type[TIntEnum], value: Union[int, str]) -> TIntEnum:
  67. """Convert text or a value into an enumerated type, if possible.
  68. *value*, the ``int`` or ``str`` to convert.
  69. Raises a class-specific exception if a ``str`` is provided that
  70. cannot be converted.
  71. Raises ``ValueError`` if the value is out of range.
  72. Returns an enumeration from the calling class corresponding to the
  73. value, if one is defined, or an ``int`` otherwise.
  74. """
  75. if isinstance(value, str):
  76. return cls.from_text(value)
  77. cls._check_value(value)
  78. return cls(value)
  79. @classmethod
  80. def _maximum(cls):
  81. raise NotImplementedError # pragma: no cover
  82. @classmethod
  83. def _short_name(cls):
  84. return cls.__name__.lower()
  85. @classmethod
  86. def _prefix(cls):
  87. return ""
  88. @classmethod
  89. def _extra_from_text(cls, text): # pylint: disable=W0613
  90. return None
  91. @classmethod
  92. def _extra_to_text(cls, value, current_text): # pylint: disable=W0613
  93. return current_text
  94. @classmethod
  95. def _unknown_exception_class(cls):
  96. return ValueError