跳转到主要内容

Python中Common Lisp的条件系统的实现。

项目描述

Python中Common Lisp的条件系统的实现。

自由软件:BSD许可协议。

理由

Common Lisp (CL) 具有一个非常丰富的条件系统。CL中的条件是一种信号,不仅用于异常处理,还用于某些其他模式。有一个非常好的解释它们是如何工作的——来自Peter Seibel的《实用Common Lisp》一书的一个章节:《超越异常处理:条件和重启》:超越异常处理:条件和重启

Python的异常只覆盖了这本书中的一个场景,但Common Lisp的条件允许更有趣的用法,特别是“重启”。重启是在异常被触发后继续代码执行的一种方式,而不需要撤销调用栈。我再重复一遍:不需要撤销调用栈。

此外,条件允许库的作者定义多个情况以处理异常。

示例

下面是一个来自该书的示例,但使用conditions库在Python中实现

def parse_log_entry(text):
    """This function does all real job on log line parsing.
    it setup two cases for restart parsing if a line
    with wrong format was found.

    Restarts:
    - use_value: just retuns an object it was passed. This can
      be any value.
    - reparse: calls `parse_log_entry` again with other text value.
      Beware, this call can lead to infinite recursion.
    """
    text = text.strip()

    if well_formed_log_entry_p(text):
        return LogEntry(text)
    else:
        def use_value(obj):
            return obj
        def reparse(text):
            return parse_log_entry(text)

        with restarts(use_value,
                      reparse) as call:
            return call(signal, MalformedLogEntryError(text))


def log_analyzer(path):
    """This procedure replaces every line which can't be parsed
    with special object MalformedLogEntry.
    """
    with handle(MalformedLogEntryError,
                  lambda (c):
                      invoke_restart('use_value',
                                     MalformedLogEntry(c.text))):
        for filename in find_all_logs(path):
            analyze_log(filename)


def log_analyzer2(path):
    """This procedure considers every line which can't be parsed
    as a line with ERROR level.
    """
    with handle(MalformedLogEntryError,
                  lambda (c):
                      invoke_restart('reparse',
                                     'ERROR: ' + c.text)):
        for filename in find_all_logs(path):
            analyze_log(filename)

这里有一个名为 parse_log_entry 的函数,它定义了两种处理异常情况的方法:use_valuereparse。但是,如何处理不良行由高级函数 log_analyser 决定。原始书籍的章节只有一个版本的 log_analyser,但我添加了一个替代的 log_analyser2 来说明为什么重启是一个有用的模式。这种模式的优点在于可以将决策代码从低级库函数移动到高级业务逻辑。

该示例的完整版本可以在 example/example.py 文件中找到。

安装

pip install conditions

文档

https://python-cl-conditions.readthedocs.org/

开发

要运行所有测试,请运行

tox

注意,要合并来自所有 tox 环境的覆盖率数据,请运行

Windows

set PYTEST_ADDOPTS=--cov-append
tox

其他

PYTEST_ADDOPTS=--cov-append tox

变更日志

0.2.0 (2016-04-05)

  • 添加了上下文管理器 restarts,现在 restart 管理器只接收一个函数,并返回一个函数,类似于调用要重启的代码。

0.1.0 (2016-03-29)

  • 首次发布在 PyPI 上。

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解有关 安装包 的更多信息。

源分发

conditions-0.2.0.tar.gz (19.3 kB 查看哈希值)

上传时间

由以下机构支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面