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

如何配置YAPF以Polars风格格式化带链式方法的调用参数?

配置YAPF实现Polars链式调用的缩进对齐格式化

需求说明

在使用Polars构建数据转换DSL时,我们希望链式方法调用(如pl.col().str.extract().cast())能以层级缩进对齐的方式格式化,提升代码可读性,示例如下:

df = df.select(
    event_type=pl.col("log_entry")
        .str.extract(r"Event Type: ([\w ]+)")
        .cast(pl.Utf8),
    event_duration=pl.col("log_entry")
        .str.extract(r"Duration: (\d+)")
        .cast(pl.Int32),
)

但YAPF默认配置下,链式调用的后续行只会与上一行起始位置左对齐,可读性较差:

df = df.select(
    event_type=pl.col("log_entry")
    .str.extract(r"Event Type: ([\w ]+)")
    .cast(pl.Utf8),
    event_duration=pl.col("log_entry")
    .str.extract(r"Duration: (\d+)")
    .cast(pl.Int32),
)

配置步骤

1. 创建/修改YAPF配置文件

在项目根目录创建或修改以下任一配置文件:

  • .yapf(纯INI格式)
  • setup.cfg(在[yapf]小节下)
  • pyproject.toml(在[tool.yapf]小节下)

2. 添加关键配置参数

方式1:使用.yapf文件

[style]
based_on_style = pep8
indent_width = 4
continuation_indent_width = 8
align_closing_bracket_with_visual_indent = true

方式2:使用pyproject.toml

[tool.yapf]
based_on_style = "pep8"
indent_width = 4
continuation_indent_width = 8
align_closing_bracket_with_visual_indent = true

参数说明

  • based_on_style = pep8:基于PEP8风格扩展,保证基础格式合规
  • indent_width = 4:基础缩进宽度(符合Python惯例)
  • continuation_indent_width = 8:链式调用的后续行使用双倍基础缩进,形成层级感
  • align_closing_bracket_with_visual_indent = true:让闭合括号与参数的起始视觉位置对齐,保持格式统一

3. 应用格式化

运行以下命令对指定文件进行格式化(-i参数表示直接修改原文件):

yapf -i your_polars_script.py

如果使用VS Code等编辑器,可配置自动保存时触发YAPF格式化,确保代码始终符合预期格式。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 07:35:13