跳转到主要内容

forge (python签名)

项目描述

forge logo

forge (python) signatures for fun and profit

pypi project MIT license Python 3.5+ master Travis CI Status master Coveralls Status Documentation Status

forge 是一个优雅的 Python 包,用于在运行时修改函数签名。这个库的目的是帮助您编写更好、更易于理解的代码,同时减少样板代码。

安装

forge 是一个仅适用于 Python 的包,托管在 PyPI 上,适用于 Python 3.5+

推荐安装方法是使用 pip-installing 安装到 虚拟环境

$ pip install python-forge

示例

考虑一个像 requests 这样的库,它提供了一个用于执行 HTTP 请求的有用 API。每个 HTTP 方法都有自己的函数,它是围绕 requests.Session.request 的一个薄包装器。代码超过 150 行,其中大约 90% 是样板代码。使用 forge 我们可以将代码大小减少到当前的约 10%,同时 提高 代码的可读性。

import forge
import requests

request = forge.copy(requests.Session.request, exclude='self')(requests.request)

def with_method(method):
    revised = forge.modify(
        'method', default=method, bound=True,
        kind=forge.FParameter.POSITIONAL_ONLY,
    )(request)
    revised.__name__ = method.lower()
    return revised

post = with_method('POST')
get = with_method('GET')
put = with_method('PUT')
delete = with_method('DELETE')
options = with_method('OPTIONS')
head = with_method('HEAD')
patch = with_method('PATCH')

发生了什么?我们首先创建了一个替代的 request 函数来替换 requests.request,它提供完全相同的功能,但使参数更明确

# requests.get() looks like this:
assert forge.repr_callable(requests.get) == 'get(url, params=None, **kwargs)'

# our get() calls the same code, but looks like this:
assert forge.repr_callable(get) == (
    'get(url, params=None, data=None, headers=None, cookies=None, '
        'files=None, auth=None, timeout=None, allow_redirects=True, '
        'proxies=None, hooks=None, stream=None, verify=None, cert=None, '
        'json=None'
    ')'
)

接下来,我们构建了一个工厂函数 with_method,它创建新的函数,这些函数使用适当的HTTP动词执行HTTP请求。由于 method 参数被绑定,因此它不会出现在结果函数的签名中。当然,这些生成的函数的签名仍然是明确的,让我们试试看。

response = get('http://google.com')
assert 'Feeling Lucky' in response.text

您可以通过访问 requests.api 的代码来查看备用代码(实际实现)。

项目信息

forge 采用了 MIT 许可证,其文档位于 Read the Docs,代码在 GitHub 上,最新版本在 PyPI 上。它在 Python 3.6+ 和 PyPy 3.5+ 上进行了严格测试。

forgeDevin Fee 编写。其他贡献者列在 https://github.com/dfee/forge/graphs/contributors 下。

项目详情


下载文件

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

源代码分发

此版本没有可用的源代码分发文件。请参阅 生成分发存档 的教程。

构建的分发

python_forge-18.6.0-py35-none-any.whl (31.3 kB 查看哈希)

上传时间 Python 3.5

由以下支持