enums for choices fields
Project description
py-enum
A python ChoiceEnum module for python3.
继承原生的 ·enum.Enum· 而来,扩展类ChoiceEnum用于以下场景:
- argparse使用
add_argument的参数choices - Django中
models.CharField的参数choices - Django REST framework
ChoiceField的参数choices
1. 安装
pip install py-enum
可查看版本变更记录ChangeLog
2. 使用(Usage)
2.1 用ChoiceEnum定义枚举
# 导入
from py_enum import ChoiceEnum
# 定义
class Color(ChoiceEnum):
RED = (1, '红色')
GREEN = (2, '绿色')
BLUE = (3, '蓝色', {'value': 'blue'})
class Status(ChoiceEnum):
PROCESSING = ('processing', '处理中')
APPROVED = ('approved', '已审批')
CANCELED = ('canceled', '已取消')
CLOSED = ('closed', '已关闭')
定义如上,按照Key = (value, label, extra)的形式进行定义,value定义的值;label是对值的描述;第三个参数是extra,额外信息,可以任意类型。
2.2 基础用法
Color.RED # Color.RED
Color.RED.value # 1
type(Color.RED) # <enum 'Color'>
str(Color.RED) # (1, 红色)
len(colors) == 3 # true
Color.RED.value in Color # true
1 in Color # true
0 not in Color # true
# 以下是在原生基础上扩展的属性和方法
Color.values # [1, 2, 3]
Color.names # ['RED', 'GREEN', 'BLUE']
Color.labels # ['红色', '绿色', '蓝色']
Color.choices # [(1, '红色'), (2, '绿色'), (3, '蓝色')]
Color.get_label(Color.RED.value) # '红色'
Color.get_extra(Color.BLUE.value) # {'value': 'blue'}
for member in Color:
print(member.value, member.label) # 直接遍历value和label
# 1, '红色'
# 2, '绿色'
# 3, '蓝色'
Color.to_js_enum()
# 输出dict数据,可以通过接口序列化后给前端使用,结合js-enumerate前端枚举库
"""
[
{"key": "RED", "value": 1, "label": "红色"},
{"key": "GREEN", "value": 2, "label": "绿色"},
{"key": "BLUE", "value": 3, "label": "蓝色", "extra": {"value": "blue"}}
]
"""
2.3 枚举对象实例化
member = Color(Color.RED.value) # 或者 Color(1)
member.value == 1 # true
member.name == 'RED' # true
member.label == '红色' # true
member.option == (1, '红色') # true
member.extra == None # true,因为没有定义
# 以上几个属性无法修改,直接赋值会抛出AttributeError异常
member.value in Color # true
2.4 在Python argparse中使用
import argparse
parser = argparse.ArgumentParser(description='test ChoiceEnum use in argparse.')
parser.add_argument('--color', type=int, choices=Color, required=True)
args = parser.parse_args(['--color', str(Color.RED.value)])
# args.color == Color.RED.value
2.5 在Django中使用
from django.db import models
class ColorModel(models.Model):
color = models.IntegerField(verbose_name='颜色', choices=Color.choices, default=Color.RED.value)
instance = ColorModel.objects.create()
assert instance.color == colors.RED.value
instance.color = colors.BLUE.value
instance.save()
2.6 在DRF中使用
from rest_framework import serializers
class ColorSerializer(serializers.Serializer):
color = serializers.ChoiceField(help_text='选择颜色', choices=Color.choices, default=Color.RED.value)
s = ColorSerializer()
s = ColorSerializer(data={'status': status.CLOSED.value})
assert s.is_valid() is True
s = ColorSerializer(data={'status': 1})
assert s.is_valid() is True
s = ColorSerializer(data={'status': 0})
assert s.is_valid() is False # 值不在枚举定义范围内,校验不通过
3. 对比
ChoiceEnum和Django的 models.Choices 的优势在于低版本Django也能使用,且普通Python项目脚本也能使用- 新增了额外的特性
- 额外多出了
ChoiceEnum.extra的用法,对不同枚举成员做映射配置相关场景可以使用 - 增加方法
ChoiceEnum.to_js_enum返回数组数据,可以用于前端枚举库 js-enumerate 初始化使用
- 额外多出了
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
py_enum-2.1.1.tar.gz
(9.8 kB
view details)
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file py_enum-2.1.1.tar.gz.
File metadata
- Download URL: py_enum-2.1.1.tar.gz
- Upload date:
- Size: 9.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.9.19
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5eb2c16b77ef867f472fd8714480b0802c63fb466fd858b04efa0f3a816a2121
|
|
| MD5 |
cf9067756a80f5468cf451b51f3662f9
|
|
| BLAKE2b-256 |
fd5ac76910499dfb2e093af427b41a84876db5c266421920a660f6e0638ce80c
|
File details
Details for the file py_enum-2.1.1-py3-none-any.whl.
File metadata
- Download URL: py_enum-2.1.1-py3-none-any.whl
- Upload date:
- Size: 7.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.9.19
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
fa89cf4b008bf869edd960d84e8178ae86d88a31a5c5e588a860b0d19b9471cc
|
|
| MD5 |
c300935d9a8773fec2f77681edd17702
|
|
| BLAKE2b-256 |
2460d372bd6e6c118ccfa3d6dc64c6dfa4a92f17f2f7c6f210d9384022ec2763
|