enumerations.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from enum import Enum, EnumMeta
  2. import cvargparse
  3. class MetaBaseType(EnumMeta):
  4. """
  5. MetaType for the base enumeration type.
  6. """
  7. def __contains__(cls, item):
  8. """
  9. Redefines the "in" operation.
  10. """
  11. if isinstance(item, str):
  12. return item.lower() in cls.as_choices()
  13. else:
  14. return super(MetaBaseType, cls).__contains__(item)
  15. def __getitem__(cls, key):
  16. """
  17. Redefines the "[]" operation.
  18. """
  19. return cls.as_choices()[key.lower()]
  20. class BaseChoiceType(Enum, metaclass=MetaBaseType):
  21. """
  22. Enum base type. Can be used to define argument choices.
  23. It also enables to quickly creat, get and display the defined choices.
  24. """
  25. @classmethod
  26. def as_choices(cls):
  27. return {e.name.lower(): e for e in cls}
  28. @classmethod
  29. def get(cls, key):
  30. if isinstance(key, str):
  31. return cls[key] if key in cls else cls.Default
  32. elif isinstance(key, cls):
  33. return key
  34. else:
  35. raise ValueError("Unknown optimizer type: \"{}\"".format(key.__class__.__name__))
  36. @classmethod
  37. def as_arg(cls, name, short_name=None, help_text=None):
  38. args = ["--{}".format(name)]
  39. if short_name is not None:
  40. args.append("-{}".format(short_name))
  41. if help_text is None:
  42. help_text = "choices for \"{}\"".format(name)
  43. help_text += " (default: {})".format(cls.Default.name.lower())
  44. return cvargparse.Arg(*args,
  45. type=str, default=cls.Default.name.lower(),
  46. choices=cls.as_choices(),
  47. help=help_text)