[英]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)
考慮到 Python 與引用一起使用的事實,您可以執行以下操作:
properties = config["network"]["connection"]["client_properties"]
properties["service"] = properties["service"].format(service=service)
使用\
:
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
)
您還可以使用變量來更好地閱讀:
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)
也就是說,我認為對於每個支架應該在哪一行 go 沒有任何共識。 (就個人而言,我從未發現任何看起來特別“正確”的選擇。)
更好的解決方案可能是引入一個臨時變量。
d = config["network"]["connection"]["client_properties"]
d["service"] = d["service"].format(service=service)
其他人正試圖將其分解為兩行,但您的問題是它仍然非常冗長。 您可以將config["network"]["connection"]["client_properties"]["service"]
分配給它自己的變量。
config_service = config["network"]["connection"]["client_properties"]["service"]
config_service = config_service.format(service=service)
# If you really need it at the original variable
config["network"]["connection"]["client_properties"]["service"] = config_service
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.