Python 3.10 PEP 634模式匹配如何实现字符串前缀通配匹配
实现方案
Python 3.10的结构模式匹配原生支持在case分支后追加if守卫条件,不需要额外开发或引入依赖,就能直接实现前缀匹配需求:
import logging # 你的原始数据 data = [ { "id": "matchme-foo", "message": "hallo this is a message", }, { "id": "matchme-bar", "message": "goodbye", }, { "id": "anotherid", "message": "completely diffrent event" } ] for event in data: match event: # 先捕获id、message字段的值,通过守卫判断id前缀 case {"id": id_val, "message": msg} if id_val.startswith("matchme-"): logging.info(msg) case {"id": "anotherid", "message": msg}: logging.error(msg)
如果你项目中多处需要做前缀匹配,也可以封装一个通用的前缀判断工具,简化重复的守卫逻辑:
def startswith(prefix: str, val: str) -> bool: return isinstance(val, str) and val.startswith(prefix) for event in data: match event: case {"id": id_val, "message": msg} if startswith("matchme-", id_val): logging.info(msg) case {"id": "anotherid", "message": msg}: logging.error(msg)
说明
上述写法完全符合原生模式匹配的语法规则,不需要拼接大量|分支,逻辑直观无额外性能损耗,适配所有Python 3.10及以上版本。
内容的提问来源于stack exchange,提问作者Martin Schroter
相关产品推荐
相关产品推荐

