enum.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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 Any, Type, TypeVar
  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) # pyright: ignore
  24. val._name_ = cls._extra_to_text(value, None) or f"{cls._prefix()}{value}"
  25. val._value_ = value # pyright: ignore
  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. return cls(value)
  50. raise cls._unknown_exception_class()
  51. @classmethod
  52. def to_text(cls: Type[TIntEnum], value: int) -> str:
  53. cls._check_value(value)
  54. try:
  55. text = cls(value).name
  56. except ValueError:
  57. text = None
  58. text = cls._extra_to_text(value, text)
  59. if text is None:
  60. text = f"{cls._prefix()}{value}"
  61. return text
  62. @classmethod
  63. def make(cls: Type[TIntEnum], value: int | str) -> TIntEnum:
  64. """Convert text or a value into an enumerated type, if possible.
  65. *value*, the ``int`` or ``str`` to convert.
  66. Raises a class-specific exception if a ``str`` is provided that
  67. cannot be converted.
  68. Raises ``ValueError`` if the value is out of range.
  69. Returns an enumeration from the calling class corresponding to the
  70. value, if one is defined, or an ``int`` otherwise.
  71. """
  72. if isinstance(value, str):
  73. return cls.from_text(value)
  74. cls._check_value(value)
  75. return cls(value)
  76. @classmethod
  77. def _maximum(cls):
  78. raise NotImplementedError # pragma: no cover
  79. @classmethod
  80. def _short_name(cls):
  81. return cls.__name__.lower()
  82. @classmethod
  83. def _prefix(cls) -> str:
  84. return ""
  85. @classmethod
  86. def _extra_from_text(cls, text: str) -> Any | None: # pylint: disable=W0613
  87. return None
  88. @classmethod
  89. def _extra_to_text(cls, value, current_text): # pylint: disable=W0613
  90. return current_text
  91. @classmethod
  92. def _unknown_exception_class(cls) -> Type[Exception]:
  93. return ValueError