enum.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. class IntEnum(enum.IntEnum):
  18. @classmethod
  19. def _check_value(cls, value):
  20. max = cls._maximum()
  21. if value < 0 or value > max:
  22. name = cls._short_name()
  23. raise ValueError(f"{name} must be between >= 0 and <= {max}")
  24. @classmethod
  25. def from_text(cls, text):
  26. text = text.upper()
  27. try:
  28. return cls[text]
  29. except KeyError:
  30. pass
  31. prefix = cls._prefix()
  32. if text.startswith(prefix) and text[len(prefix):].isdigit():
  33. value = int(text[len(prefix):])
  34. cls._check_value(value)
  35. try:
  36. return cls(value)
  37. except ValueError:
  38. return value
  39. raise cls._unknown_exception_class()
  40. @classmethod
  41. def to_text(cls, value):
  42. cls._check_value(value)
  43. try:
  44. return cls(value).name
  45. except ValueError:
  46. return f"{cls._prefix()}{value}"
  47. @classmethod
  48. def make(cls, value):
  49. """Convert text or a value into an enumerated type, if possible.
  50. *value*, the ``int`` or ``str`` to convert.
  51. Raises a class-specific exception if a ``str`` is provided that
  52. cannot be converted.
  53. Raises ``ValueError`` if the value is out of range.
  54. Returns an enumeration from the calling class corresponding to the
  55. value, if one is defined, or an ``int`` otherwise.
  56. """
  57. if isinstance(value, str):
  58. return cls.from_text(value)
  59. cls._check_value(value)
  60. try:
  61. return cls(value)
  62. except ValueError:
  63. return value
  64. @classmethod
  65. def _maximum(cls):
  66. raise NotImplementedError # pragma: no cover
  67. @classmethod
  68. def _short_name(cls):
  69. return cls.__name__.lower()
  70. @classmethod
  71. def _prefix(cls):
  72. return ''
  73. @classmethod
  74. def _unknown_exception_class(cls):
  75. return ValueError