表示下一行代码的最佳 Python 方式是什么?
What is the best Python way to represent next line of code?
基本思路是这样写一行:
url = 'https://{host}?key={key}&lang={lang}&text='.format(**data) + '&text='.join(words)
想用 PEP 8 风格重写它,所以写了这个:
url = 'https://{host}?key={key}&lang={lang}&text='.format(**data) \
+ '&text='.join(words)
哪一个是正确的?
如果两者都不是,我想听听为什么,看看你会怎么写。
根据 Python Style Guide,一行的最大长度应为 79 个字符,但“对于结构限制较少(文档字符串或注释)的流动长文本块,行长度应限制为 72字符。”
然而,在编写代码时,如何真正格式化代码取决于个人品味,有些人不会为大于 79 个字符的行所困扰(尽管出于准备目的坚持这样做是值得赞赏的)而其他人可能喜欢少于 79 个字符的行。
也没有?我可能很想采用为此设计的方法,例如:
from urllib.parse import urlencode
host = 'example.com'
data = {'key': 'foo', 'lang': 'bar', 'text': 'baz'}
url = 'https://{host}?{query}'.format(host=host, query=urlencode(data))
这会给你 url
的:
'https://example.com?key=foo&lang=bar&text=baz'
urlencode
函数可以处理这种情况——即使是您的单词列表:
from urllib.parse import urlencode
host = 'example.com'
data = {'key': 'asdf', 'lang': 'en-us', 'text': ['sam', 'i', 'am']}
params = urlencode(data, True)
url2 = 'https://{host}?' + params
这将产生:https://example.com?key=asdf&lang=en-us&text=sam&text=i&text=am
请注意,调用 urlencode
时 doseq
参数设置为 True
以处理您的重复参数列表。
基本思路是这样写一行:
url = 'https://{host}?key={key}&lang={lang}&text='.format(**data) + '&text='.join(words)
想用 PEP 8 风格重写它,所以写了这个:
url = 'https://{host}?key={key}&lang={lang}&text='.format(**data) \
+ '&text='.join(words)
哪一个是正确的?
如果两者都不是,我想听听为什么,看看你会怎么写。
根据 Python Style Guide,一行的最大长度应为 79 个字符,但“对于结构限制较少(文档字符串或注释)的流动长文本块,行长度应限制为 72字符。”
然而,在编写代码时,如何真正格式化代码取决于个人品味,有些人不会为大于 79 个字符的行所困扰(尽管出于准备目的坚持这样做是值得赞赏的)而其他人可能喜欢少于 79 个字符的行。
也没有?我可能很想采用为此设计的方法,例如:
from urllib.parse import urlencode
host = 'example.com'
data = {'key': 'foo', 'lang': 'bar', 'text': 'baz'}
url = 'https://{host}?{query}'.format(host=host, query=urlencode(data))
这会给你 url
的:
'https://example.com?key=foo&lang=bar&text=baz'
urlencode
函数可以处理这种情况——即使是您的单词列表:
from urllib.parse import urlencode
host = 'example.com'
data = {'key': 'asdf', 'lang': 'en-us', 'text': ['sam', 'i', 'am']}
params = urlencode(data, True)
url2 = 'https://{host}?' + params
这将产生:https://example.com?key=asdf&lang=en-us&text=sam&text=i&text=am
请注意,调用 urlencode
时 doseq
参数设置为 True
以处理您的重复参数列表。