一种使用动态成员定义枚举的更 Pythonic 的方法 [英] A more pythonic way to define an enum with dynamic members

查看:19
本文介绍了一种使用动态成员定义枚举的更 Pythonic 的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个枚举来表示 ISO 国家/地区代码.国家/地区代码数据来自一个 json 文件,可以从以下位置获得:https://github.com/lukes/ISO-3166-Countries-with-Regional-Codes

I needed to create an enum to represent the ISO country codes. The country code data comes from a json file which can be obtained from: https://github.com/lukes/ISO-3166-Countries-with-Regional-Codes

所以我所做的是:

data = json.load(open('slim-2.json'))
codes_list = [(data[i]['alpha-2'], int(data[i]['country-code']))
              for i in range(len(data))]

CountryCode = enum.Enum('CountryCode', codes_list,)

names_dict = {int(data[i]['country-code']):data[i]['name'] 
              for i in range(len(data))}
setattr(CountryCode, '_names', names_dict)

CountryCode.choices = classmethod(lambda cls:((member.value, name) 
                                  for name, member in cls.__members__.items()))
setattr(CountryCode, '__str__' ,lambda self: self.__class__._names[self.value])

坦率地说,这段代码很丑陋.我查看了定义枚举类的替代方法,但无法拼凑出解决方案.有没有办法以下列形式定义枚举:

This code snippet is frankly ugly. I looked at alternative ways to define the enum class but couldn't piece together a solution. Is there a way to define the enum in the following form:

class CountryCode(enum.Enum):

    data = json.load(open('slim-2.json'))
    # Some code to define the enum members

    @classmethod
    def choices(cls):
    # etc...

有什么关于如何做到这一点的建议吗?

Any suggestions on how to do this?

推荐答案

这个怎么样?

data = json.load(open('slim-2.json'))
CountryCode = enum.Enum('CountryCode', [
    (x['alpha-2'], int(x['country-code'])) for x in data
])
CountryCode._names = {x['alpha-2']: x['name'] for x in data}
CountryCode.__str__ = lambda self: self._names[self.name]
CountryCode.choices = lambda: ((e.value, e.name) for e in CountryCode)

  • [...data[i]... for i in range(len(data))] 替换为 [...x... for x in data];您可以不使用索引来迭代序列(列表,代码中的data).
  • 始终使用CountryCode.attr = ...;而不是混合 CountryCode.attr = ...setattr(CountryCode, 'attr', ...).
    • Replaced [...data[i]... for i in range(len(data))] with [...x... for x in data]; You can itearte sequence (list, data in the code) without using indexes.
    • Used CountryCode.attr = ... consistently; instead of mixing CountryCode.attr = ... and setattr(CountryCode, 'attr', ...).
    • 这篇关于一种使用动态成员定义枚举的更 Pythonic 的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆