A lightweight, optionally typed expression language with a custom grammar for matching arbitrary Python objects.
规则引擎
|badge-build| |badge-pypi|
这是一个轻量级、可选类型注解的表达式语言,拥有自定义语法,用于匹配任意的 Python 对象。
文档可在 https://zeroSteiner.github.io/rule-engine/ 找到。
:警告: 下一个主要版本(5.0)将移除对 Python 版本 3.6、3.7 和 3.8 的支持。目前尚未确定发布时间表。
规则引擎表达式使用其自有的语言编写,作为 Python 中的字符串定义。其语法与 Python 最相似,并从 Ruby 中汲取了一些灵感。这门语言的一些特性包括:
- 可选的类型注解
- 使用正则表达式匹配字符串
- 日期时间数据类型
- 复合数据类型(Python dict、list 和 set 类型的等价物)
- 数据属性
- 线程安全
使用示例
以下示例展示了定义规则对象并应用于两个字典的基本用法,显示其中一个匹配而另一个不匹配。更多信息请参阅 入门_。
.. code-block:: python
import rule_engine
匹配一个名字并应用正则表达式到电子邮件
rule = rule_engine.Rule( 'first_name == "Luke" and email =~ ".*@rebels.org"' ) # => <Rule text='first_name == "Luke" and email =~ ".*@rebels.org"' > rule.matches({ 'first_name': 'Luke', 'last_name': 'Skywalker', 'email': 'luke@rebels.org' }) # => True rule.matches({ 'first_name': 'Darth', 'last_name': 'Vader', 'email': 'dvader@empire.net' }) # => False
下一个示例展示了可选类型系统。创建了一个自定义上下文,定义了两个符号,一个字符串和一个浮点数。由于符号已定义,如果指定了未知符号或使用了无效操作,则会引发异常。更多信息请参阅 类型注解_。
.. code-block:: python
import rule_engine
定义带有两个符号的自定义上下文
context = rule_engine.Context(type_resolver=rule_engine.type_resolver_from_dict({ 'first_name': rule_engine.DataType.STRING, 'age': rule_engine.DataType.FLOAT }))
使用未知符号时出错
rule = rule_engine.Rule('last_name == "Vader"', context=context)
=> SymbolResolutionError: last_name
使用无效操作时出错
rule = rule_engine.Rule('first_name + 1', context=context)
=> EvaluationError: data type mismatch
想尝试规则表达式语言吗?使用 调试 REPL_ 进行试验,安装后只需运行 python -m rule_engine.debug_repl。
安装
使用 pip install rule-engine 从 PyPi 安装最新版本。发布版本遵循 语义化版本控制,以表明每个新版本是修复了错误、添加了新特性还是破坏了向后兼容性。详情请参阅 更新日志。
致谢
- Spencer McIntyre - zeroSteiner |social-github|
许可证
规则引擎库遵循 BSD 3-Clause 许可证发布。它可用于商业和个人目的。更多信息请参阅 LICENSE_ 文件。
.. |badge-build| image:: https://img.shields.io/github/actions/workflow/status/zeroSteiner/rule-engine/ci.yml?branch=master&style=flat-square :alt: GitHub Workflow Status (branch) :target: https://github.com/zeroSteiner/rule-engine/actions/workflows/ci.yml
.. |badge-pypi| image:: https://img.shields.io/pypi/v/rule-engine?style=flat-square :alt: PyPI :target: https://pypi.org/project/rule-engine/
.. |social-github| image:: https://img.shields.io/github/followers/zeroSteiner?style=social :alt: GitHub followers :target: https://github.com/zeroSteiner
.. _Change Log: https://zerosteiner.github.io/rule-engine/change_log.html .. _Debug REPL: https://zerosteiner.github.io/rule-engine/debug_repl.html .. _Getting Started: https://zerosteiner.github.io/rule-engine/getting_started.html .. _LICENSE: https://github.com/zeroSteiner/rule-engine/blob/master/LICENSE .. _Semantic Versioning: https://semver.org/ .. _Type Hinting: https://zerosteiner.github.io/rule-engine/getting_started.html#type-hinting
项目介绍
A lightweight, optionally typed expression language with a custom grammar for matching arbitrary Python objects.
定制我的领域