[issue18720] Switch suitable constants in the socket module to IntEnum

Christian Heimes report at bugs.python.org
Wed Aug 14 15:56:04 CEST 2013


Christian Heimes added the comment:

The manual list of AF_ prefixes looks ugly. We are going to run into the same problem for every module. How about an additional constructor that takes a name, dict and string prefix?

class IntEnum(int, Enum):
    @classmethod
    def from_moduledict(cls, name, moddict, prefix):
        members = {name: value for name, value in moddict.items()
                   if name.startswith(prefix)}
        return cls(name, members)

>>> import socket, enum, pprint
>>> AddressFamily = enum.IntEnum.from_moduledict("AddressFamily", socket.__dict__, "AF_")
>>> pprint.pprint(dict(AddressFamily.__members__))
{'AF_APPLETALK': <AddressFamily.AF_APPLETALK: 5>,
 'AF_ASH': <AddressFamily.AF_ASH: 18>,
 'AF_ATMPVC': <AddressFamily.AF_ATMPVC: 8>,
 'AF_ATMSVC': <AddressFamily.AF_ATMSVC: 20>,
 'AF_AX25': <AddressFamily.AF_AX25: 3>,
 'AF_BLUETOOTH': <AddressFamily.AF_BLUETOOTH: 31>,
 'AF_BRIDGE': <AddressFamily.AF_BRIDGE: 7>,
 'AF_CAN': <AddressFamily.AF_CAN: 29>,
 'AF_DECnet': <AddressFamily.AF_DECnet: 12>,
 'AF_ECONET': <AddressFamily.AF_ECONET: 19>,
 'AF_INET': <AddressFamily.AF_INET: 2>,
 'AF_INET6': <AddressFamily.AF_INET6: 10>,
 'AF_IPX': <AddressFamily.AF_IPX: 4>,
 'AF_IRDA': <AddressFamily.AF_IRDA: 23>,
 'AF_KEY': <AddressFamily.AF_KEY: 15>,
 'AF_LLC': <AddressFamily.AF_LLC: 26>,
 'AF_NETBEUI': <AddressFamily.AF_NETBEUI: 13>,
 'AF_NETLINK': <AddressFamily.AF_NETLINK: 16>,
 'AF_NETROM': <AddressFamily.AF_NETROM: 6>,
 'AF_PACKET': <AddressFamily.AF_PACKET: 17>,
 'AF_PPPOX': <AddressFamily.AF_PPPOX: 24>,
 'AF_RDS': <AddressFamily.AF_RDS: 21>,
 'AF_ROSE': <AddressFamily.AF_ROSE: 11>,
 'AF_ROUTE': <AddressFamily.AF_NETLINK: 16>,
 'AF_SECURITY': <AddressFamily.AF_SECURITY: 14>,
 'AF_SNA': <AddressFamily.AF_SNA: 22>,
 'AF_TIPC': <AddressFamily.AF_TIPC: 30>,
 'AF_UNIX': <AddressFamily.AF_UNIX: 1>,
 'AF_UNSPEC': <AddressFamily.AF_UNSPEC: 0>,
 'AF_WANPIPE': <AddressFamily.AF_WANPIPE: 25>,
 'AF_X25': <AddressFamily.AF_X25: 9>}

----------
nosy: +christian.heimes

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue18720>
_______________________________________


More information about the Python-bugs-list mailing list