如何用多个括号对打破一条长线?

How to break a long line with multiple bracket pairs?

如何在 PEP 8 的 79 个字符限制之后用多个括号对打破长行?

config["network"]["connection"]["client_properties"]["service"] = config["network"]["connection"]["client_properties"]["service"].format(service=service)

使用 black,自以为是的、可重现的代码格式化程序:

config["network"]["connection"]["client_properties"][
    "service"
] = config["network"]["connection"]["client_properties"][
    "service"
].format(
    service=service
)

使用 \:

config["network"]["connection"]["client_properties"]["service"] = \
    config["network"]["connection"]["client_properties"]["service"].format(
        service=service
    )

您也可以使用变量来更好地阅读:

client_service = config["network"]["connection"]["client_properties"]["service"]
client_service = client_service.format(service=service)

# If you are using the value later in your code keeping it in an variable may
# increase readability
...
# else you can put it back
config["network"]["connection"]["client_properties"]["service"] = client_service

方括号允许隐式续行。例如,

config["network"
]["connection"
]["client_properties"
]["service"] = config["network"]["connection"]["client_properties"]["service"].format(
service=service)

也就是说,我认为对于每个括号应该放在哪一行上没有任何共识。 (就我个人而言,我从未找到 任何 看起来特别 "right" 的选择。)

更好的解决方案可能是引入一个临时变量。

d = config["network"]["connection"]["client_properties"]
d["service"] = d["service"].format(service=service)

考虑到 Python 与引用一起工作的事实,您可以执行以下操作:

properties = config["network"]["connection"]["client_properties"]
properties["service"] = properties["service"].format(service=service)