[英]When is semicolon use in Python considered “good” or “acceptable”?
Python is a "whitespace delimited" language. Python是一种“以空格分隔”的语言。 However, the use of semicolons are allowed.
然而,使用分号是允许的。 For example, the following works but is frowned upon:
例如,以下工作但不赞成:
print("Hello!");
print("This is valid");
I've been using python for several years now, and the only time I have ever used semicolons is in generating one-time command-line scripts with python: 我已经使用python好几年了,而且我用过分号的唯一一次是用python生成一次性命令行脚本:
python -c "import inspect, mymodule; print(inspect.getfile(mymodule))"
or adding code in comments on SO (ie "you should try import os; print os.path.join(a,b)
") 或者在SO的评论中添加代码(即“你应该尝试
import os; print os.path.join(a,b)
”)
I also noticed in this answer to a similar question that the semicolon can also be used to make one line if
blocks, as in 我也注意到在这个回答类似的问题了分号,也可以用来制作一条线
if
块,如
if x < y < z: print(x); print(y); print(z)
which is convenient for the two usage examples I gave (command-line scripts and comments). 这对我给出的两个用法示例(命令行脚本和注释)很方便。
The above examples are for communicating code in paragraph form or making short snippets, but not something I would expect in a production codebase. 以上示例用于以段落形式传递代码或制作简短的代码段,但不是我在生产代码库中所期望的。
Here is my question: in python, is there ever a reason to use the semicolon in a production code? 这是我的问题:在python中,是否有理由在生产代码中使用分号? I imagine that they were added to the language solely for the reasons I have cited, but its always possible that Guido had a grander scheme in mind.
我想他们只是因为我引用的原因而被添加到语言中,但是Guido总是有可能考虑到更宏伟的计划。 No opinions please;
没有意见; I'm looking either for examples from existing code where the semicolon was useful, or some kind of statement from the python docs or from Guido about the use of the semicolon.
我正在寻找分号有用的现有代码中的示例,或者来自python docs或Guido关于分号使用的某种语句。
PEP 8 is the official style guide and says: PEP 8是官方风格指南,并说:
Compound statements (multiple statements on the same line) are generally discouraged.
通常不鼓励使用复合语句(同一行上的多个语句)。
(See also the examples just after this in the PEP.) (另请参阅PEP之后的示例。)
While I don't agree with everything PEP 8 says, if you're looking for an authoritative source, that's it. 虽然我不同意PEP 8所说的一切,但如果你正在寻找一个权威的来源,就是这样。 You should use multi-statement lines only as a last resort.
您应该仅使用多语句行作为最后的手段。 (
python -c
is a good example of such a last resort, because you have no way to use actual linebreaks in that case.) (
python -c
是这种最后手段的一个很好的例子,因为在这种情况下你无法使用实际的换行符。)
I use semicolons in code all of the time. 我一直在代码中使用分号。 Our code folds across lines quite frequently, and a semicolon is a definitive assertion that a statement is ending.
我们的代码经常跨行折叠,分号是一个声明结束的明确断言。
output, errors, status = generate_output_with_errors_and_status(
first_monstrous_functional_argument(argument_one_to_argument
, argument_two_to_argument)
, second_argument);
See? 看到? They're quite helpful to readability.
它们对可读性非常有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.