我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用enum.IntEnum()。
def test_programatic_function_type_from_subclass(self): SummerMonth = IntEnum('SummerMonth', 'june july august') lst = list(SummerMonth) self.assertEqual(len(lst), len(SummerMonth)) self.assertEqual(len(SummerMonth), 3, SummerMonth) self.assertEqual( [SummerMonth.june, SummerMonth.july, SummerMonth.august], lst, ) for i, month in enumerate('june july august'.split()): i += 1 e = SummerMonth(i) self.assertEqual(e, i) self.assertEqual(e.name, month) self.assertTrue(e in SummerMonth) self.assertTrue(type(e) is SummerMonth)
def test_programatic_function_unicode_type_from_subclass(self): SummerMonth = IntEnum('SummerMonth', unicode('june july august')) lst = list(SummerMonth) self.assertEqual(len(lst), len(SummerMonth)) self.assertEqual(len(SummerMonth), 3, SummerMonth) self.assertEqual( [SummerMonth.june, SummerMonth.july, SummerMonth.august], lst, ) for i, month in enumerate(unicode('june july august').split()): i += 1 e = SummerMonth(i) self.assertEqual(e, i) self.assertEqual(e.name, month) self.assertTrue(e in SummerMonth) self.assertTrue(type(e) is SummerMonth)
def test_introspection(self): class Number(IntEnum): one = 100 two = 200 self.assertTrue(Number.one._member_type_ is int) self.assertTrue(Number._member_type_ is int) class String(str, Enum): yarn = 'soft' rope = 'rough' wire = 'hard' self.assertTrue(String.yarn._member_type_ is str) self.assertTrue(String._member_type_ is str) class Plain(Enum): vanilla = 'white' one = 1 self.assertTrue(Plain.vanilla._member_type_ is object) self.assertTrue(Plain._member_type_ is object)
def check_net_address(addr, family): """Check a net address validity. Supported families are IPv4, IPv6 and MAC addresses. """ if enum and PY3: assert isinstance(family, enum.IntEnum), family if family == AF_INET: octs = [int(x) for x in addr.split('.')] assert len(octs) == 4, addr for num in octs: assert 0 <= num <= 255, addr if not PY3: addr = unicode(addr) ipaddress.IPv4Address(addr) elif family == AF_INET6: assert isinstance(addr, str), addr if not PY3: addr = unicode(addr) ipaddress.IPv6Address(addr) elif family == psutil.AF_LINK: assert re.match('([a-fA-F0-9]{2}[:|\-]?){6}', addr) is not None, addr else: raise ValueError("unknown family %r", family)
def allValues(ctype): if issubclass(ctype, IntEnum): return list(ctype) if issubclass(ctype, Structure): names, types = zip(*ctype._fields) values = [allValues(t) for t in types] def make(vals): obj = ctype() for name, val in zip(names, vals): setattr(obj, name, val) return obj return [make(vals) for vals in product(*values)] # TODO: handle bounded ints via _fields # TODO: handle arrays raise TypeError("Unsupported type %s" % ctype)
def test_unique_dirty(self): with self.assertRaisesRegex(ValueError, 'tres.*one'): @unique class Dirty(Enum): one = 1 two = 'dos' tres = 1 with self.assertRaisesRegex( ValueError, 'double.*single.*turkey.*triple', ): @unique class Dirtier(IntEnum): single = 1 double = 1 triple = 3 turkey = 3
def set_register(self, register_name, value): """ Writes a CPU register. @param int, str, or CPURegister(IntEnum) register_name: CPU register to write. @param int value: Value to write. """ if not self._is_u32(value): raise ValueError('The value parameter must be an unsigned 32-bit value.') if not self._is_enum(register_name, CpuRegister): raise ValueError('Parameter register_name must be of type int, str or CpuRegister enumeration.') register_name = self._decode_enum(register_name, CpuRegister) if register_name is None: raise ValueError('Parameter register_name must be of type int, str or CpuRegister enumeration.') register_name = ctypes.c_int(register_name.value) value = ctypes.c_uint32(value) self.jlink.JLINKARM_WriteReg(register_name, value)
def get_register(self, register_name): """ Reads a CPU register. @param int, str, or CPURegister(IntEnum) register_name: CPU register to read. @return int: Value read. """ if not self._is_enum(register_name, CpuRegister): raise ValueError('Parameter register_name must be of type int, str or CpuRegister enumeration.') register_name = self._decode_enum(register_name, CpuRegister) if register_name is None: raise ValueError('Parameter register_name must be of type int, str or CpuRegister enumeration.') register_name = ctypes.c_int(register_name.value) #value = ctypes.c_uint32() return self.jlink.JLINKARM_ReadReg(register_name)
def test_introspection(self): class Number(IntEnum): one = 100 two = 200 self.assertIs(Number.one._member_type_, int) self.assertIs(Number._member_type_, int) class String(str, Enum): yarn = 'soft' rope = 'rough' wire = 'hard' self.assertIs(String.yarn._member_type_, str) self.assertIs(String._member_type_, str) class Plain(Enum): vanilla = 'white' one = 1 self.assertIs(Plain.vanilla._member_type_, object) self.assertIs(Plain._member_type_, object)
def __new__(cls, int_value, range_min, range_max): obj = super(IntEnum, cls).__new__(cls, int_value) obj._value_ = int_value obj._range_min = range_min obj._range_max = range_max return obj
def sockfam_to_enum(num): """Convert a numeric socket family value to an IntEnum member. If it's not a known member, return the numeric value itself. """ if enum is None: return num else: # pragma: no cover try: return socket.AddressFamily(num) except (ValueError, AttributeError): return num
def socktype_to_enum(num): """Convert a numeric socket type value to an IntEnum member. If it's not a known member, return the numeric value itself. """ if enum is None: return num else: # pragma: no cover try: return socket.AddressType(num) except (ValueError, AttributeError): return num
def setUp(self): class Season(Enum): SPRING = 1 SUMMER = 2 AUTUMN = 3 WINTER = 4 self.Season = Season class Konstants(float, Enum): E = 2.7182818 PI = 3.1415926 TAU = 2 * PI self.Konstants = Konstants class Grades(IntEnum): A = 5 B = 4 C = 3 D = 2 F = 0 self.Grades = Grades class Directional(str, Enum): EAST = 'east' WEST = 'west' NORTH = 'north' SOUTH = 'south' self.Directional = Directional from datetime import date class Holiday(date, Enum): NEW_YEAR = 2013, 1, 1 IDES_OF_MARCH = 2013, 3, 15 self.Holiday = Holiday
def test_intenum_inherited(self): class IntEnum(int, Enum): pass class phy(IntEnum): pi = 3 tau = 2 * pi self.assertTrue(phy.pi < phy.tau)
def test_intenum(self): class WeekDay(IntEnum): SUNDAY = 1 MONDAY = 2 TUESDAY = 3 WEDNESDAY = 4 THURSDAY = 5 FRIDAY = 6 SATURDAY = 7 self.assertEqual(['a', 'b', 'c'][WeekDay.MONDAY], 'c') self.assertEqual([i for i in range(WeekDay.TUESDAY)], [0, 1, 2]) lst = list(WeekDay) self.assertEqual(len(lst), len(WeekDay)) self.assertEqual(len(WeekDay), 7) target = 'SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY' target = target.split() for i, weekday in enumerate(target): i += 1 e = WeekDay(i) self.assertEqual(e, i) self.assertEqual(int(e), i) self.assertEqual(e.name, weekday) self.assertTrue(e in WeekDay) self.assertEqual(lst.index(e)+1, i) self.assertTrue(0 < e < 8) self.assertTrue(type(e) is WeekDay) self.assertTrue(isinstance(e, int)) self.assertTrue(isinstance(e, Enum))
def test_intenum_duplicates(self): class WeekDay(IntEnum): __order__ = 'SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY' SUNDAY = 1 MONDAY = 2 TUESDAY = TEUSDAY = 3 WEDNESDAY = 4 THURSDAY = 5 FRIDAY = 6 SATURDAY = 7 self.assertTrue(WeekDay.TEUSDAY is WeekDay.TUESDAY) self.assertEqual(WeekDay(3).name, 'TUESDAY') self.assertEqual([k for k,v in WeekDay.__members__.items() if v.name != k], ['TEUSDAY', ])
def test_intenum_transitivity(self): class number(IntEnum): one = 1 two = 2 three = 3 class numero(IntEnum): uno = 1 dos = 2 tres = 3 self.assertEqual(number.one, numero.uno) self.assertEqual(number.two, numero.dos) self.assertEqual(number.three, numero.tres)
def test_wrong_enum_in_mixed_call(self): class Monochrome(IntEnum): black = 0 white = 1 class Gender(Enum): male = 0 female = 1 self.assertRaises(ValueError, Monochrome, Gender.male)
def test_mixed_enum_in_call_1(self): class Monochrome(IntEnum): black = 0 white = 1 class Gender(IntEnum): male = 0 female = 1 self.assertTrue(Monochrome(Gender.female) is Monochrome.white)
def test_multiple_mixin_mro(self): class auto_enum(EnumMeta): def __new__(metacls, cls, bases, classdict): original_dict = classdict classdict = enum._EnumDict() for k, v in original_dict.items(): classdict[k] = v temp = type(classdict)() names = set(classdict._member_names) i = 0 for k in classdict._member_names: v = classdict[k] if v == (): v = i else: i = v i += 1 temp[k] = v for k, v in classdict.items(): if k not in names: temp[k] = v return super(auto_enum, metacls).__new__( metacls, cls, bases, temp) AutoNumberedEnum = auto_enum('AutoNumberedEnum', (Enum,), {}) AutoIntEnum = auto_enum('AutoIntEnum', (IntEnum,), {}) class TestAutoNumber(AutoNumberedEnum): a = () b = 3 c = () class TestAutoInt(AutoIntEnum): a = () b = 3 c = ()
def test_inherited_new_from_mixed_enum(self): class AutoNumber3(IntEnum): def __new__(cls): value = len(cls.__members__) + 1 obj = int.__new__(cls, value) obj._value_ = value return obj class Color(AutoNumber3): red = () green = () blue = () self.assertEqual(len(Color), 3, "wrong number of elements: %d (should be %d)" % (len(Color), 3)) Color.red Color.green Color.blue
def test_empty_with_functional_api(self): empty = enum.IntEnum('Foo', {}) self.assertEqual(len(empty), 0)