A more pythonic way to define an enum with dynamic members

前端 未结 3 2205
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-06 13:32

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-Cou

3条回答
  •  囚心锁ツ
    2021-01-06 14:11

    How about 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)
    
    • 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', ...).

提交回复
热议问题