从str或bytes继承的enum的优雅实现

AnyStrEnum的Python项目详细描述


任何强度

Python 3.7PyPi Package Version

从str或bytes继承的枚举的优雅实现

就这么简单

fromanystrenumimportStrEnumclassSeason(StrEnum):spring:strsummer:strautumn:strwinter:strprint(Season.summer)print(isinstance(Season.summer,str))# summer# True

功能

  • 使用类型提示轻松分配成员(不需要使用auto()或其他存根)
  • 支持自定义转换器或分隔符的自动值生成
  • 方法来筛选成员(containscontained_instartswithendswith等)
  • 自定义strbytes类型支持

安装

$ pip install AnyStrEnum

示例

使用自定义单词分隔符

若要自动将名称中的所有下划线(_)替换为更合适的值,请使用sep参数:

fromanystrenumimportStrEnumclassRegion(StrEnum,sep='-'):us_east_1:strus_west_1:strca_central_1:strcn_northwest_1:streu_central_1:streu_west_1:streu_north_2:strsa_east_1:strprint(Region.us_east_1)# us-east-1

使用str转换器和自定义单词分隔符

如果需要对名称应用更多更改,可以使用converter参数。在此处传递一个将对每个成员调用的函数

fromanystrenumimportStrEnumclassContentType(StrEnum,converter=lambdas:s.replace('_','/',1),sep='-'):application_json:strapplication_octet_stream:strapplication_x_json_stream:straudio_mpeg:straudio_pcm:straudio_ogg:strprint(ContentType.application_octet_stream)# application/octet-stream

从一个例子中可以看到,首先,名称将使用lambda函数进行转换,然后, 其余下划线将替换为给定的分隔符

筛选枚举成员

使用前面示例中的枚举
print(ContentType.filter(contains='-',startswith='a',endswith='m'))# {<ContentType.application_octet_stream: 'application/octet-stream'>,# <ContentType.application_x_json_stream: 'application/x-json-stream'>}print(ContentType.filter(contained_in='Usually content type for MP3 is audio/mpeg'))# {<ContentType.audio_mpeg: 'audio/mpeg'>}print(Region.filter(startswith='eu',endswith='1'))# {<Region.eu_west_1: 'eu-west-1'>, <Region.eu_central_1: 'eu-central-1'>}

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
带有嵌套JAR的java RCP ClassNotFoundException   java在输入框中设置默认值,crud应用程序使用spring   java如何在Heroku中使用fs创建新文件   java将JPanel放在JFrame中   java这个正则表达式会匹配“i.imgur.com/xxx”吗?   java在片段内创建RecylerView,而无需在Android中设置片段   Android上Groovy导致java错误的双精度浮点精度损失   swing Java查找JFrame属于JPanel的内容   java Spring junit自连线自定义类本身必须有构造函数吗?   java textswitcher支持前面的文本   从Android客户端到JAXRS的java Post自定义对象   java如何检索JSON数据并使用MPAndroidChart绘制折线图,以及在安卓上的改进   拒绝用户“root”@“localhost”的java c3p0访问(使用密码“是”)   使用Selenium Webdriver自动化ExtJS应用程序时java面临的问题