Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:
来自c#背景的变量和方法名的命名约定通常是CamelCase或Pascal案例:
// C# example
string thisIsMyVariable = "a"
public void ThisIsMyMethod()
In Python, I have seen the above but I have also seen underscores being used:
在Python中,我已经看到了上面的内容,但我也看到了使用的下划线:
# python example
this_is_my_variable = 'a'
def this_is_my_function():
Is there a more preferable, definitive coding style for Python?
Python是否有一种更可取的、确定的编码风格?
12 个解决方案
#1
636
See Python PEP 8.
看到Python PEP 8。
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
函数名应该是小写的,单词之间用下划线分隔,以提高可读性。
mixedCase is allowed only in contexts where that's already the prevailing style
mixedCase只允许在已经是流行样式的上下文中使用
Variables...
变量……
Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.
使用函数命名规则:小写,单词之间用下划线分隔,以提高可读性。
Personally, I deviate from this because I also prefer mixedCase
over lower_case
for my own projects.
就我个人而言,我偏离了这一点,因为在我自己的项目中,我也更喜欢mixedCase而不是小写。
#2
485
Google Python Style Guide has the following convention:
谷歌Python风格指南有以下约定:
module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_CONSTANT_NAME, global_var_name, instance_var_name, function_parameter_name, local_var_name
module_name、package_name、ClassName、method_name、ExceptionName、function_name、GLOBAL_CONSTANT_NAME、global_var_name、instance_var_name、function_parameter_name、local_var_name
A similar naming scheme should be applied to a CLASS_CONSTANT_NAME
类似的命名方案应该应用于CLASS_CONSTANT_NAME
#3
192
David Goodger (in "Code Like a Pythonista" here) describes the PEP 8 recommendations as follows:
David Goodger(在《像Pythonista这样的代码》中)描述了PEP 8的建议如下:
-
joined_lower
for functions, methods, attributes, variablesjoined_lower用于函数、方法、属性和变量
-
joined_lower
orALL_CAPS
for constants用于常量的joined_lower或ALL_CAPS
-
StudlyCaps
for classesStudlyCaps类
-
camelCase
only to conform to pre-existing conventionscamelCase只符合已有的约定
#4
37
As the Style Guide for Python Code admits,
正如Python代码的风格指南所承认的那样,
The naming conventions of Python's library are a bit of a mess, so we'll never get this completely consistent
Python库的命名约定有点混乱,所以我们永远不会得到完全一致的结果
Note that this refers just to Python's standard library. If they can't get that consistent, then there hardly is much hope of having a generally-adhered-to convention for all Python code, is there?
注意,这只涉及到Python的标准库。如果他们不能得到那样的一致,那么对于所有的Python代码来说,几乎没有什么希望有一个普遍遵守的约定,是吗?
From that, and the discussion here, I would deduce that it's not a horrible sin if one keeps using e.g. Java's or C#'s (clear and well-established) naming conventions for variables and functions when crossing over to Python. Keeping in mind, of course, that it is best to abide with whatever the prevailing style for a codebase / project / team happens to be. As the Python Style Guide points out, internal consistency matters most.
从这一点以及这里的讨论中,我可以推断,如果我们一直在使用Java或c#的命名约定(清晰而明确),比如在切换到Python时,为变量和函数命名。当然,请记住,对于代码库/项目/团队来说,最好遵循任何流行的样式。正如Python风格指南所指出的,内部一致性最重要。
Feel free to dismiss me as a heretic. :-) Like the OP, I'm not a "Pythonista", not yet anyway.
你可以把我当作异教徒来开除。-)和OP一样,我也不是“毕达哥拉斯主义者”,至少现在还不是。
#5
31
There is PEP 8, as other answers show, but PEP 8 is only the styleguide for the standard library, and it's only taken as gospel therein. One of the most frequent deviations of PEP 8 for other pieces of code is the variable naming, specifically for methods. There is no single predominate style, although considering the volume of code that uses mixedCase, if one were to make a strict census one would probably end up with a version of PEP 8 with mixedCase. There is little other deviation from PEP 8 that is quite as common.
有PEP 8,如其他答案所示,但PEP 8只是标准库的样式指南,在其中只被当作福音。PEP 8对其他代码块最常见的偏差之一是变量命名,特别是对方法的命名。虽然考虑到使用mixedCase的代码量,但是没有单一的占主导地位的样式,如果要进行严格的普查,很可能会得到一个带有mixedCase的PEP 8的版本。与PEP 8几乎没有其他类似的偏离。
#6
27
As mentioned, PEP 8 says to use lower_case_with_underscores
for variables, methods and functions.
如前所述,PEP 8表示对变量、方法和函数使用小写_case_with_下划线。
I prefer using lower_case_with_underscores
for variables and mixedCase
for methods and functions makes the code more explicit and readable. Thus following the Zen of Python's "explicit is better than implicit" and "Readability counts"
我更喜欢对变量使用小写的case_with_下划线,对方法和函数使用混合格可以使代码更显式和可读。因此,遵循Python的“显式优于隐式”和“可读性”的原则
#7
15
Personally I try to use CamelCase for classes, mixedCase methods and functions. Variables are usually underscore separated (when I can remember). This way I can tell at a glance what exactly I'm calling, rather than everything looking the same.
我个人尝试使用CamelCase类、mixedCase方法和函数。变量通常下划线分隔(当我记得的时候)。这样,我一眼就能看出我在说什么,而不是所有看起来都一样的东西。
#8
14
Most python people prefer underscores, but even I am using python since more than 5 years right now, I still do not like them. They just look ugly to me, but maybe that's all the Java in my head.
大多数python用户更喜欢下划线,但是即使我现在使用python已经超过5年了,我还是不喜欢它们。它们在我看来很丑,但也许这就是我脑子里的想法。
I simply like CamelCase better since it fits better with the way classes are named, It feels more logical to have SomeClass.doSomething()
than SomeClass.do_something()
. If you look around in the global module index in python, you will find both, which is due to the fact that it's a collection of libraries from various sources that grew overtime and not something that was developed by one company like Sun with strict coding rules. I would say the bottom line is: Use whatever you like better, it's just a question of personal taste.
我只是更喜欢CamelCase,因为它更适合类的命名方式,使用SomeClass.doSomething()比使用SomeClass.do_something()更合理。如果你在python的全局模块索引中查找,你会发现两者都有,这是因为它是来自各种来源的库的集合,随着时间的推移而增长,而不是像Sun这样的公司用严格的编码规则开发的。我想说的底线是:用你喜欢的任何东西,这只是个人品味的问题。
#9
6
There is a paper about this: http://www.cs.kent.edu/~jmaletic/papers/ICPC2010-CamelCaseUnderScoreClouds.pdf
有一篇关于这方面的论文:http://www.cs.kent.edu/~jmaletic/papers/ICPC2010-CamelCaseUnderScoreClouds.pdf
If you are lazy to read it it says that snake_case is more readable than camelCase. That's why modern languages use (or should use) snake wherever they can.
如果你懒得读的话,它说snake_case比camelCase更容易读。这就是为什么现代语言使用(或应该使用)蛇的原因。
Conclusoin from the paper,
Conclusoin的纸,
An eye-tracking study analyzing the effect of identifier style (camel-case and underscore) on accuracy, time, and visual effort is presented with respect to the task of recognizing a correct identifier, given a phrase. Visual effort is determined using six measures based on eye gaze data namely: fixation counts and durations. Although, no difference was found between identifier styles with respect to accuracy, results indicate a significant improvement in time and lower visual effort with the underscore style. The interaction of Experience with Style indicates that novices benefit twice as much with respect to time, with the underscore style. This implies that with experience or training, the performance difference between styles is reduced. These results add to the findings of Binkley et al.’s study [4]. Future work includes conducting more eyetracking studies (with a larger subset of identifiers and larger subject sample), on reading source code consisting of both identifier styles, in the context of a specific task such as debugging. Another possible direction is to determine if there is an advantage for a programmer to change their current style to what is determined to be a better overall style.
摘要针对识别标识符的任务,提出了一种识别标识符风格(驼背式和下划线式)对人眼精度、时间和视觉效果的跟踪研究。视觉效果是用基于眼睛凝视数据的六种测量方法来确定的:固定计数和持续时间。尽管在准确性方面,标识符样式之间没有差异,结果表明在时间上有显著的改进,下划线样式的视觉效果较低。经验与风格的交互作用表明,新手对时间的益处是下划线的两倍。这意味着,通过经验或培训,风格之间的性能差异会减少。这些结果增加了Binkley等人的研究结果[4]。未来的工作包括进行更多的眼球追踪研究(有更大的标识符子集和更大的主题样本),在阅读源代码中包含两种标识符样式,在特定任务(如调试)的上下文中。另一个可能的方向是确定程序员是否有优势将他们当前的样式更改为更好的整体样式。
#10
2
The coding style is usually part of an organization's internal policy/convention standards, but I think in general, the all_lower_case_underscore_separator style (also called snake_case) is most common in python.
编码风格通常是组织内部策略/约定标准的一部分,但我认为,一般来说,all_lower_case_underscore_separator风格(也称为snake_case)在python中最常见。
#11
1
Typically, one follow the conventions used in the language's standard library.
通常,人们遵循语言的标准库中使用的约定。
#12
1
further to what @JohnTESlade has answered. Google's python style guide has some pretty neat recommendations,
接下来是@JohnTESlade的回答。谷歌的python风格指南有一些非常简洁的建议,
Names to Avoid
名称,以避免
- single character names except for counters or iterators
- 除计数器或迭代器外的单个字符名称
- dashes (-) in any package/module name
- 任何包/模块名中的破折号(-)
-
\__double_leading_and_trailing_underscore__ names
(reserved by Python) - \__double_leading_and_trailing_underscore__(由Python保留)
Naming Convention
命名约定
- "Internal" means internal to a module or protected or private within a class.
- “内部”是指模块的内部或类中的受保护或私有。
- Prepending a single underscore (_) has some support for protecting module variables and functions (not included with import * from). Prepending a double underscore (__) to an instance variable or method effectively serves to make the variable or method private to its class (using name mangling).
- 前置一个下划线(_)支持保护模块变量和函数(不包括import * from)。在实例变量或方法前面加上双下划线(__)可以有效地使变量或方法成为类的私有属性(使用名称管理)。
- Place related classes and top-level functions together in a module. Unlike Java, there is no need to limit yourself to one class per module.
- 将相关的类和*函数放在一个模块中。与Java不同,不需要将每个模块限制为一个类。
- Use
CapWords
for class names, butlower_with_under.py
for module names. Although there are many existing modules namedCapWords.py
, this is now discouraged because it's confusing when the module happens to be named after a class. ("wait -- did I write import StringIO or from StringIO import StringIO?") - 类名使用CapWords,但使用lower_with_under。py模块的名字。虽然有许多现有的模块叫做CapWords。py,现在不建议这样做,因为当模块以类命名时,会很混乱。(“等等——我是写导入StringIO还是从StringIO导入StringIO?”)
Guidelines derived from Guido's Recommendations
准则源自圭多的建议
#1
636
See Python PEP 8.
看到Python PEP 8。
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
函数名应该是小写的,单词之间用下划线分隔,以提高可读性。
mixedCase is allowed only in contexts where that's already the prevailing style
mixedCase只允许在已经是流行样式的上下文中使用
Variables...
变量……
Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.
使用函数命名规则:小写,单词之间用下划线分隔,以提高可读性。
Personally, I deviate from this because I also prefer mixedCase
over lower_case
for my own projects.
就我个人而言,我偏离了这一点,因为在我自己的项目中,我也更喜欢mixedCase而不是小写。
#2
485
Google Python Style Guide has the following convention:
谷歌Python风格指南有以下约定:
module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_CONSTANT_NAME, global_var_name, instance_var_name, function_parameter_name, local_var_name
module_name、package_name、ClassName、method_name、ExceptionName、function_name、GLOBAL_CONSTANT_NAME、global_var_name、instance_var_name、function_parameter_name、local_var_name
A similar naming scheme should be applied to a CLASS_CONSTANT_NAME
类似的命名方案应该应用于CLASS_CONSTANT_NAME
#3
192
David Goodger (in "Code Like a Pythonista" here) describes the PEP 8 recommendations as follows:
David Goodger(在《像Pythonista这样的代码》中)描述了PEP 8的建议如下:
-
joined_lower
for functions, methods, attributes, variablesjoined_lower用于函数、方法、属性和变量
-
joined_lower
orALL_CAPS
for constants用于常量的joined_lower或ALL_CAPS
-
StudlyCaps
for classesStudlyCaps类
-
camelCase
only to conform to pre-existing conventionscamelCase只符合已有的约定
#4
37
As the Style Guide for Python Code admits,
正如Python代码的风格指南所承认的那样,
The naming conventions of Python's library are a bit of a mess, so we'll never get this completely consistent
Python库的命名约定有点混乱,所以我们永远不会得到完全一致的结果
Note that this refers just to Python's standard library. If they can't get that consistent, then there hardly is much hope of having a generally-adhered-to convention for all Python code, is there?
注意,这只涉及到Python的标准库。如果他们不能得到那样的一致,那么对于所有的Python代码来说,几乎没有什么希望有一个普遍遵守的约定,是吗?
From that, and the discussion here, I would deduce that it's not a horrible sin if one keeps using e.g. Java's or C#'s (clear and well-established) naming conventions for variables and functions when crossing over to Python. Keeping in mind, of course, that it is best to abide with whatever the prevailing style for a codebase / project / team happens to be. As the Python Style Guide points out, internal consistency matters most.
从这一点以及这里的讨论中,我可以推断,如果我们一直在使用Java或c#的命名约定(清晰而明确),比如在切换到Python时,为变量和函数命名。当然,请记住,对于代码库/项目/团队来说,最好遵循任何流行的样式。正如Python风格指南所指出的,内部一致性最重要。
Feel free to dismiss me as a heretic. :-) Like the OP, I'm not a "Pythonista", not yet anyway.
你可以把我当作异教徒来开除。-)和OP一样,我也不是“毕达哥拉斯主义者”,至少现在还不是。
#5
31
There is PEP 8, as other answers show, but PEP 8 is only the styleguide for the standard library, and it's only taken as gospel therein. One of the most frequent deviations of PEP 8 for other pieces of code is the variable naming, specifically for methods. There is no single predominate style, although considering the volume of code that uses mixedCase, if one were to make a strict census one would probably end up with a version of PEP 8 with mixedCase. There is little other deviation from PEP 8 that is quite as common.
有PEP 8,如其他答案所示,但PEP 8只是标准库的样式指南,在其中只被当作福音。PEP 8对其他代码块最常见的偏差之一是变量命名,特别是对方法的命名。虽然考虑到使用mixedCase的代码量,但是没有单一的占主导地位的样式,如果要进行严格的普查,很可能会得到一个带有mixedCase的PEP 8的版本。与PEP 8几乎没有其他类似的偏离。
#6
27
As mentioned, PEP 8 says to use lower_case_with_underscores
for variables, methods and functions.
如前所述,PEP 8表示对变量、方法和函数使用小写_case_with_下划线。
I prefer using lower_case_with_underscores
for variables and mixedCase
for methods and functions makes the code more explicit and readable. Thus following the Zen of Python's "explicit is better than implicit" and "Readability counts"
我更喜欢对变量使用小写的case_with_下划线,对方法和函数使用混合格可以使代码更显式和可读。因此,遵循Python的“显式优于隐式”和“可读性”的原则
#7
15
Personally I try to use CamelCase for classes, mixedCase methods and functions. Variables are usually underscore separated (when I can remember). This way I can tell at a glance what exactly I'm calling, rather than everything looking the same.
我个人尝试使用CamelCase类、mixedCase方法和函数。变量通常下划线分隔(当我记得的时候)。这样,我一眼就能看出我在说什么,而不是所有看起来都一样的东西。
#8
14
Most python people prefer underscores, but even I am using python since more than 5 years right now, I still do not like them. They just look ugly to me, but maybe that's all the Java in my head.
大多数python用户更喜欢下划线,但是即使我现在使用python已经超过5年了,我还是不喜欢它们。它们在我看来很丑,但也许这就是我脑子里的想法。
I simply like CamelCase better since it fits better with the way classes are named, It feels more logical to have SomeClass.doSomething()
than SomeClass.do_something()
. If you look around in the global module index in python, you will find both, which is due to the fact that it's a collection of libraries from various sources that grew overtime and not something that was developed by one company like Sun with strict coding rules. I would say the bottom line is: Use whatever you like better, it's just a question of personal taste.
我只是更喜欢CamelCase,因为它更适合类的命名方式,使用SomeClass.doSomething()比使用SomeClass.do_something()更合理。如果你在python的全局模块索引中查找,你会发现两者都有,这是因为它是来自各种来源的库的集合,随着时间的推移而增长,而不是像Sun这样的公司用严格的编码规则开发的。我想说的底线是:用你喜欢的任何东西,这只是个人品味的问题。
#9
6
There is a paper about this: http://www.cs.kent.edu/~jmaletic/papers/ICPC2010-CamelCaseUnderScoreClouds.pdf
有一篇关于这方面的论文:http://www.cs.kent.edu/~jmaletic/papers/ICPC2010-CamelCaseUnderScoreClouds.pdf
If you are lazy to read it it says that snake_case is more readable than camelCase. That's why modern languages use (or should use) snake wherever they can.
如果你懒得读的话,它说snake_case比camelCase更容易读。这就是为什么现代语言使用(或应该使用)蛇的原因。
Conclusoin from the paper,
Conclusoin的纸,
An eye-tracking study analyzing the effect of identifier style (camel-case and underscore) on accuracy, time, and visual effort is presented with respect to the task of recognizing a correct identifier, given a phrase. Visual effort is determined using six measures based on eye gaze data namely: fixation counts and durations. Although, no difference was found between identifier styles with respect to accuracy, results indicate a significant improvement in time and lower visual effort with the underscore style. The interaction of Experience with Style indicates that novices benefit twice as much with respect to time, with the underscore style. This implies that with experience or training, the performance difference between styles is reduced. These results add to the findings of Binkley et al.’s study [4]. Future work includes conducting more eyetracking studies (with a larger subset of identifiers and larger subject sample), on reading source code consisting of both identifier styles, in the context of a specific task such as debugging. Another possible direction is to determine if there is an advantage for a programmer to change their current style to what is determined to be a better overall style.
摘要针对识别标识符的任务,提出了一种识别标识符风格(驼背式和下划线式)对人眼精度、时间和视觉效果的跟踪研究。视觉效果是用基于眼睛凝视数据的六种测量方法来确定的:固定计数和持续时间。尽管在准确性方面,标识符样式之间没有差异,结果表明在时间上有显著的改进,下划线样式的视觉效果较低。经验与风格的交互作用表明,新手对时间的益处是下划线的两倍。这意味着,通过经验或培训,风格之间的性能差异会减少。这些结果增加了Binkley等人的研究结果[4]。未来的工作包括进行更多的眼球追踪研究(有更大的标识符子集和更大的主题样本),在阅读源代码中包含两种标识符样式,在特定任务(如调试)的上下文中。另一个可能的方向是确定程序员是否有优势将他们当前的样式更改为更好的整体样式。
#10
2
The coding style is usually part of an organization's internal policy/convention standards, but I think in general, the all_lower_case_underscore_separator style (also called snake_case) is most common in python.
编码风格通常是组织内部策略/约定标准的一部分,但我认为,一般来说,all_lower_case_underscore_separator风格(也称为snake_case)在python中最常见。
#11
1
Typically, one follow the conventions used in the language's standard library.
通常,人们遵循语言的标准库中使用的约定。
#12
1
further to what @JohnTESlade has answered. Google's python style guide has some pretty neat recommendations,
接下来是@JohnTESlade的回答。谷歌的python风格指南有一些非常简洁的建议,
Names to Avoid
名称,以避免
- single character names except for counters or iterators
- 除计数器或迭代器外的单个字符名称
- dashes (-) in any package/module name
- 任何包/模块名中的破折号(-)
-
\__double_leading_and_trailing_underscore__ names
(reserved by Python) - \__double_leading_and_trailing_underscore__(由Python保留)
Naming Convention
命名约定
- "Internal" means internal to a module or protected or private within a class.
- “内部”是指模块的内部或类中的受保护或私有。
- Prepending a single underscore (_) has some support for protecting module variables and functions (not included with import * from). Prepending a double underscore (__) to an instance variable or method effectively serves to make the variable or method private to its class (using name mangling).
- 前置一个下划线(_)支持保护模块变量和函数(不包括import * from)。在实例变量或方法前面加上双下划线(__)可以有效地使变量或方法成为类的私有属性(使用名称管理)。
- Place related classes and top-level functions together in a module. Unlike Java, there is no need to limit yourself to one class per module.
- 将相关的类和*函数放在一个模块中。与Java不同,不需要将每个模块限制为一个类。
- Use
CapWords
for class names, butlower_with_under.py
for module names. Although there are many existing modules namedCapWords.py
, this is now discouraged because it's confusing when the module happens to be named after a class. ("wait -- did I write import StringIO or from StringIO import StringIO?") - 类名使用CapWords,但使用lower_with_under。py模块的名字。虽然有许多现有的模块叫做CapWords。py,现在不建议这样做,因为当模块以类命名时,会很混乱。(“等等——我是写导入StringIO还是从StringIO导入StringIO?”)
Guidelines derived from Guido's Recommendations
准则源自圭多的建议