You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python的durable-rules中对规则语句取反?

在durable-rules中实现语句取反的正确方式

你之前用!符号的写法逻辑有误,导致取反不生效。问题出在:anyItem(!条件)的含义是存在至少一个元素不满足条件,这和你想要的“所有元素都不满足条件(从未有AWV检查/就诊)”完全不是一个逻辑。

以下是两种正确的实现方式:

方式1:使用noneItem方法(推荐)

noneItem是durable-rules内置的集合方法,直接表示集合中没有任何元素满足指定条件,完全匹配你的需求:

with ruleset('awv'):
    @when_all(m.visits.anyItem(item.cpt_codes.anyItem(item.matches('G0438') | item.matches('G0439'))))
    def had_awv_exam_or_awv_visit_more_than_12_month(c):
        print('had_awv_exam_or_awv_visit_more_than_12_month')
    
    # 正确的取反规则:没有任何就诊记录的CPT码包含G0438/G0439
    @when_all(m.visits.noneItem(item.cpt_codes.anyItem(item.matches('G0438') | item.matches('G0439'))))
    def never_awv_exam_or_awv_visit(c):
        print('no_awv_exam_or_awv_visit')

方式2:用not()包裹整个表达式

如果习惯用否定符号,可以用not()把整个anyItem表达式包裹起来,实现“不存在符合条件的元素”的逻辑:

with ruleset('awv'):
    @when_all(m.visits.anyItem(item.cpt_codes.anyItem(item.matches('G0438') | item.matches('G0439'))))
    def had_awv_exam_or_awv_visit_more_than_12_month(c):
        print('had_awv_exam_or_awv_visit_more_than_12_month')
    
    @when_all(not(m.visits.anyItem(item.cpt_codes.anyItem(item.matches('G0438') | item.matches('G0439')))))
    def never_awv_exam_or_awv_visit(c):
        print('no_awv_exam_or_awv_visit')

关键说明

  • 原代码的anyItem(!...)逻辑错误:只要有一条就诊记录的CPT码不包含目标值,就会触发规则,哪怕其他记录包含目标值,这显然不是你要的“从未有AWV”效果。
  • 推荐用noneItem,语义更清晰,也更符合durable-rules的集合操作习惯。

内容的提问来源于stack exchange,提问作者vee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 12:15:32