Python enum.IntEnum() Examples

The following are 30 code examples of enum.IntEnum(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module enum , or try the search function .
Example #1
Source File: test_enum.py    From oss-ftp with MIT License 6 votes vote down vote up
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) 
Example #2
Source File: ctype_util.py    From phillip with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #3
Source File: error_msg.py    From python-openflow with MIT License 6 votes vote down vote up
def get_class(self):
        """Return a Code class based on current ErrorType value.

        Returns:
            enum.IntEnum: class referenced by current error type.

        """
        classes = {'OFPET_HELLO_FAILED': HelloFailedCode,
                   'OFPET_BAD_REQUEST': BadRequestCode,
                   'OFPET_BAD_ACTION': BadActionCode,
                   'OFPET_BAD_INSTRUCTION': BadInstructionCode,
                   'OFPET_BAD_MATCH': BadMatchCode,
                   'OFPET_FLOW_MOD_FAILED': FlowModFailedCode,
                   'OFPET_GROUP_MOD_FAILED': GroupModFailedCode,
                   'OFPET_PORT_MOD_FAILED': PortModFailedCode,
                   'OFPET_QUEUE_OP_FAILED': QueueOpFailedCode,
                   'OFPET_SWITCH_CONFIG_FAILED': SwitchConfigFailedCode,
                   'OFPET_ROLE_REQUEST_FAILED': RoleRequestFailedCode,
                   'OFPET_METER_MOD_FAILED': MeterModFailedCode,
                   'OFPET_TABLE_MOD_FAILED': TableModFailedCode,
                   'OFPET_TABLE_FEATURES_FAILED': TableFeaturesFailedCode}
        return classes.get(self.name, GenericFailedCode) 
Example #4
Source File: __init__.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def check_net_address(addr, family):
    """Check a net address validity. Supported families are IPv4,
    IPv6 and MAC addresses.
    """
    import ipaddress  # python >= 3.3 / requires "pip install ipaddress"
    if enum and PY3:
        assert isinstance(family, enum.IntEnum), family
    if family == socket.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 == socket.AF_INET6:
        assert isinstance(addr, str), addr
        if not PY3:
            addr = unicode(addr)
        ipaddress.IPv6Address(addr)
    elif family == psutil.AF_LINK:
        assert re.match(r'([a-fA-F0-9]{2}[:|\-]?){6}', addr) is not None, addr
    else:
        raise ValueError("unknown family %r", family) 
Example #5
Source File: test_enum.py    From oss-ftp with MIT License 6 votes vote down vote up
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) 
Example #6
Source File: test_enum.py    From oss-ftp with MIT License 6 votes vote down vote up
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) 
Example #7
Source File: test_enum.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #8
Source File: ctype_util.py    From gym-dolphin with MIT License 6 votes vote down vote up
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) 
Example #9
Source File: test.py    From tandem with Apache License 2.0 6 votes vote down vote up
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) 
Example #10
Source File: test.py    From tandem with Apache License 2.0 6 votes vote down vote up
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) 
Example #11
Source File: test.py    From tandem with Apache License 2.0 6 votes vote down vote up
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) 
Example #12
Source File: _common.py    From teleport with Apache License 2.0 5 votes vote down vote up
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:
            return num 
Example #13
Source File: test_enum.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_mixed_enum_in_call_2(self):
        class Monochrome(Enum):
            black = 0
            white = 1
        class Gender(IntEnum):
            male = 0
            female = 1
        self.assertIs(Monochrome(Gender.male), Monochrome.black) 
Example #14
Source File: test_enum.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_inherited_new_from_mixed_enum(self):
        class AutoNumber(IntEnum):
            def __new__(cls):
                value = len(cls.__members__) + 1
                obj = int.__new__(cls, value)
                obj._value_ = value
                return obj
        class Color(AutoNumber):
            red = ()
            green = ()
            blue = ()
        self.assertEqual(list(Color), [Color.red, Color.green, Color.blue])
        self.assertEqual(list(map(int, Color)), [1, 2, 3]) 
Example #15
Source File: test_enum.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_multiple_mixin_mro(self):
        class auto_enum(type(Enum)):
            def __new__(metacls, cls, bases, classdict):
                temp = type(classdict)()
                names = set(classdict._member_names)
                i = 0
                for k in classdict._member_names:
                    v = classdict[k]
                    if v is Ellipsis:
                        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)

        class AutoNumberedEnum(Enum, metaclass=auto_enum):
            pass

        class AutoIntEnum(IntEnum, metaclass=auto_enum):
            pass

        class TestAutoNumber(AutoNumberedEnum):
            a = ...
            b = 3
            c = ...

        class TestAutoInt(AutoIntEnum):
            a = ...
            b = 3
            c = ... 
Example #16
Source File: test_enum.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_unique_clean(self):
        @unique
        class Clean(Enum):
            one = 1
            two = 'dos'
            tres = 4.0
        @unique
        class Cleaner(IntEnum):
            single = 1
            double = 2
            triple = 3 
Example #17
Source File: error_msg.py    From python-openflow with MIT License 5 votes vote down vote up
def __init__(self, xid=None, error_type=None, code=None, data=b''):
        """Assign parameters to object attributes.

        Args:
            xid (int): To be included in the message header.
            error_type (:class:`ErrorType`): Error type.
            code (enum.IntEnum): Error code.
            data (bytes): Its content is based on the error type and code.
        """
        super().__init__(xid)
        self.error_type = error_type
        self.code = code
        self.data = data 
Example #18
Source File: error_msg.py    From python-openflow with MIT License 5 votes vote down vote up
def get_class(self):
        """Return a Code class based on current ErrorType value.

        Returns:
            enum.IntEnum: class referenced by current error type.

        """
        classes = {'OFPET_HELLO_FAILED': HelloFailedCode,
                   'OFPET_BAD_REQUEST': BadRequestCode,
                   'OFPET_BAD_ACTION': BadActionCode,
                   'OFPET_FLOW_MOD_FAILED': FlowModFailedCode,
                   'OFPET_PORT_MOD_FAILED': PortModFailedCode,
                   'OFPET_QUEUE_OP_FAILED': QueueOpFailedCode}
        return classes.get(self.name, GenericFailedCode) 
Example #19
Source File: test_enum.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #20
Source File: ctype_util.py    From phillip with GNU General Public License v3.0 5 votes vote down vote up
def randomValue(ctype):
  if issubclass(ctype, IntEnum):
    return random.choice(list(ctype))
  
  if issubclass(ctype, Structure):
    obj = ctype()
    for name, type_ in ctype._fields:
      setattr(obj, name, randomValue(type_))
    return obj
  
  # TODO: handle arrays
  raise TypeError("Unsupported type %s" % ctype)

# TODO: fill out the rest of this table 
Example #21
Source File: ctype_util.py    From phillip with GNU General Public License v3.0 5 votes vote down vote up
def toCType(t):
  if issubclass(t, IntEnum):
    return c_uint
  return t

# class decorator 
Example #22
Source File: bigtable.py    From airflow with Apache License 2.0 5 votes vote down vote up
def __init__(self,  # pylint: disable=too-many-arguments
                 instance_id: str,
                 main_cluster_id: str,
                 main_cluster_zone: str,
                 project_id: Optional[str] = None,
                 replica_cluster_id: Optional[str] = None,
                 replica_cluster_zone: Optional[str] = None,
                 instance_display_name: Optional[str] = None,
                 instance_type: Optional[IntEnum] = None,
                 instance_labels: Optional[int] = None,
                 cluster_nodes: Optional[int] = None,
                 cluster_storage_type: Optional[IntEnum] = None,
                 timeout: Optional[float] = None,
                 gcp_conn_id: str = 'google_cloud_default',
                 *args, **kwargs) -> None:
        self.project_id = project_id
        self.instance_id = instance_id
        self.main_cluster_id = main_cluster_id
        self.main_cluster_zone = main_cluster_zone
        self.replica_cluster_id = replica_cluster_id
        self.replica_cluster_zone = replica_cluster_zone
        self.instance_display_name = instance_display_name
        self.instance_type = instance_type
        self.instance_labels = instance_labels
        self.cluster_nodes = cluster_nodes
        self.cluster_storage_type = cluster_storage_type
        self.timeout = timeout
        self._validate_inputs()
        self.gcp_conn_id = gcp_conn_id
        super().__init__(*args, **kwargs) 
Example #23
Source File: test_unicode.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_formatting_with_enum(self):
        # issue18780
        import enum
        class Float(float, enum.Enum):
            PI = 3.1415926
        class Int(enum.IntEnum):
            IDES = 15
        class Str(str, enum.Enum):
            ABC = 'abc'
        # Testing Unicode formatting strings...
        self.assertEqual("%s, %s" % (Str.ABC, Str.ABC),
                         'Str.ABC, Str.ABC')
        self.assertEqual("%s, %s, %d, %i, %u, %f, %5.2f" %
                        (Str.ABC, Str.ABC,
                         Int.IDES, Int.IDES, Int.IDES,
                         Float.PI, Float.PI),
                         'Str.ABC, Str.ABC, 15, 15, 15, 3.141593,  3.14')

        # formatting jobs delegated from the string implementation:
        self.assertEqual('...%(foo)s...' % {'foo':Str.ABC},
                         '...Str.ABC...')
        self.assertEqual('...%(foo)s...' % {'foo':Int.IDES},
                         '...Int.IDES...')
        self.assertEqual('...%(foo)i...' % {'foo':Int.IDES},
                         '...15...')
        self.assertEqual('...%(foo)d...' % {'foo':Int.IDES},
                         '...15...')
        self.assertEqual('...%(foo)u...' % {'foo':Int.IDES, 'def':Float.PI},
                         '...15...')
        self.assertEqual('...%(foo)f...' % {'foo':Float.PI,'def':123},
                         '...3.141593...') 
Example #24
Source File: _common.py    From teleport with Apache License 2.0 5 votes vote down vote up
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.SocketKind(num)
        except ValueError:
            return num 
Example #25
Source File: _common.py    From teleport with Apache License 2.0 5 votes vote down vote up
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:
            return num 
Example #26
Source File: _common.py    From teleport with Apache License 2.0 5 votes vote down vote up
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 
Example #27
Source File: _common.py    From teleport with Apache License 2.0 5 votes vote down vote up
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 
Example #28
Source File: cli.py    From httprunner with Apache License 2.0 5 votes vote down vote up
def main_run(extra_args) -> enum.IntEnum:
    capture_message("start to run")
    # keep compatibility with v2
    extra_args = ensure_cli_args(extra_args)

    tests_path_list = []
    extra_args_new = []
    for item in extra_args:
        if not os.path.exists(item):
            # item is not file/folder path
            extra_args_new.append(item)
        else:
            # item is file/folder path
            tests_path_list.append(item)

    if len(tests_path_list) == 0:
        # has not specified any testcase path
        logger.error(f"No valid testcase path in cli arguments: {extra_args}")
        sys.exit(1)

    testcase_path_list = main_make(tests_path_list)
    if not testcase_path_list:
        logger.error("No valid testcases found, exit 1.")
        sys.exit(1)

    if "--tb=short" not in extra_args_new:
        extra_args_new.append("--tb=short")

    extra_args_new.extend(testcase_path_list)
    logger.info(f"start to run tests with pytest. HttpRunner version: {__version__}")
    return pytest.main(extra_args_new) 
Example #29
Source File: test_enum.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_unique_dirty(self):
        try:
            class Dirty(Enum):
                __order__ = 'one two tres'
                one = 1
                two = 'dos'
                tres = 1
            unique(Dirty)
        except ValueError:
            exc = sys.exc_info()[1]
            message = exc.args[0]
        self.assertTrue('tres -> one' in message)

        try:
            class Dirtier(IntEnum):
                __order__ = 'single double triple turkey'
                single = 1
                double = 1
                triple = 3
                turkey = 3
            unique(Dirtier)
        except ValueError:
            exc = sys.exc_info()[1]
            message = exc.args[0]
        self.assertTrue('double -> single' in message)
        self.assertTrue('turkey -> triple' in message) 
Example #30
Source File: test_enum.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_unique_clean(self):
        class Clean(Enum):
            one = 1
            two = 'dos'
            tres = 4.0
        unique(Clean)
        class Cleaner(IntEnum):
            single = 1
            double = 2
            triple = 3
        unique(Cleaner)