在python中用户友好地实现enum
easy-enum的Python项目详细描述
python的文档化Enum类型的用户友好实现 语言。
安装
$ pip install easy_enum
要从shell中的master branch execute安装最新版本 以下命令:
$ pip install -U https://github.com/molejar/pyEnum/archive/master.zip
如果要进行开发,请从以下源安装pyenum:
$ git clone https://github.com/molejar/pyEnum.git
$ cd pyEnum
$ pip install -U -e .
运行这些命令可能会遇到权限问题。这里有一个 很少有解决方法:
- 使用sudo运行以全局安装pyenum和依赖项
- 指定--user选项以本地安装到您的家庭中 目录(如果没有,则将“~/.local/bin”导出到路径变量中)。
- 在 virtualenv本地到 特定项目工作集。
用法
下面的示例演示如何在 代码:
fromeasy_enumimportEnumclassTestEnum(Enum):# attribute with no description, the name will be 'FIRST_ITEM' and empty string as descriptionFIRST_ITEM=1# attribute with descriptionSECOND_ITEM=(2,'Description for second item')# attribute with description and custom string nameTHIRD_ITEM=(3,'third','Description for third item')# attribute with custom string name (the description must be specified as empty string)FOURTH_ITEM=(4,'fourth','')# Read attributes value and nameprint(TestEnum.SECOND_ITEM)# 2print(TestEnum['FIRST_ITEM'])# 1print(TestEnum[1])# 'FIRST_ITEM'print(TestEnum[3])# 'third'print(TestEnum['third'])# 3# Use get method with default value if want skip exceptionprint(TestEnum.get(8))# Noneprint(TestEnum.get('eight'))# Noneprint(TestEnum.get(8,'eight'))# 'eight'# Check if exist attribute with specific valueprint(1inTestEnum)# Trueprint(8inTestEnum)# False# Check if exist attribute with specific nameprint('first'inTestEnum)# Falseprint('third'inTestEnum)# True# Get attribute description (as parameter use attribute name or value)print(TestEnum.desc(1))# ''print(TestEnum.desc(2))# 'Description for second item'print(TestEnum.desc('third'))# 'Description for third item'# Get count of all attributesprint(len(TestEnum))# 4# Get list with all attributes namenames=[item[0]foriteminTestEnum]print(names)# ['FIRST_ITEM', 'SECOND_ITEM', 'third', 'fourth']# Get list with all attributes valuevalues=[item[1]foriteminTestEnum]print(values)# [1, 2, 3, 4]# Read all itemsforname,value,descinTestEnum:print('{} = {} ({})'.format(name,value,desc))