Python C API ---- Write Python C Extension and Call Python From C

C 语言 转 Python

解析 Python 变量

  • 函数: PyArg_ParseTuple

    • 单个 python 变量转成 C 变量
    • python tuple 转成 多个 C 变量
    • 接口 (PyArg_ParseTuple(args, "ii", &num1, &num2)

      • args: Python 所有参数
      • "ii": Python 参数的类型与个数,相当于翻译模板, "ii" 代表两个 整数
      • &num1, &num2: 使用引用指针接收,解析出来的变量
    • 返回值: 失败为零, 成功非零
1
2
3
4
5
6
7
8
9
static PyObject * Conver_Test_Max_value(PyObject *self, PyObject *args)
{
    int num1, num2;
    // "ii"表示两个整型参数
    if(!(PyArg_ParseTuple(args, "ii", &num1, &num2))){
        return NULL;
    }
    return (PyObject *)Py_BuildValue("i", Max_value(num1, num2));
}

创建 Python 变量

  • 函数: Py_BuildValue

coverage ---- Python unit test and code coverage tool 代码覆盖率探测

report 中包含大量 site-packages 模块测试

修复 report, no source code error

  • 情况一

    • 案例

      py38 run-test: commands[3] | coverage html --skip-covered
      No source for code: '/mnt/d/source/infrared_quantity/D:\source\infrared_quantity\tests\test_textrender.py'.
      Aborting report output, consider using -i.
      ERROR: InvocationError for command /mnt/d/source/infrared_quantity/.tox/py38/bin/coverage html --skip-covered (exited with code 1)
      
    • 修复方法

mypy ---- Python typing checker

missing types or stubs not installed

pyproject.toml 配置文件

  • 参考

  • 例子

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    
    # mypy global options:
    
    [tool.mypy]
    python_version = "2.7"
    warn_return_any = true
    warn_unused_configs = true
    
    # mypy per-module options:
    
    [[tool.mypy.overrides]]
    module = ["mycode.foo.*", "module2", "module3", ...]
    disallow_untyped_defs = true
    
    [[tool.mypy.overrides]]
    module = "mycode.bar"
    warn_return_any = false
    
    [[tool.mypy.overrides]]
    module = [
        "somelibrary",
        "some_other_library"
    ]
    ignore_missing_imports = true

初次启动慢

  • 正常现象

stubs

  • pandas

fastapi ---- a Python Web Framework

教程

  • 官方文档: FastAPI
  • 类似项目对比

  • 兄弟项目

    • Typer, 命令行工具

  • 相关工具

    • uvicorn

      • 用于运行 fastapi 程序
    • Starlette

      • ASGI, python 异步 web 服务框架
    • pydantic

      • 数据验证和设置工具
      • 通过 python annotations (typing) 实现
      • 在 runtime 时期强制执行 typing(type hint)
      • 类型不一致,给出错误提示