Python中变量和函数名称的命名约定是什么?

问题:Python中变量和函数名称的命名约定是什么?

来自C#背景的变量和方法名称的命名约定通常为camelCase或PascalCase:

// C# example
string thisIsMyVariable = "a"
public void ThisIsMyMethod()

在Python中,我已经看到了上述内容,但也看到了使用下划线的情况:

# python example
this_is_my_variable = 'a'
def this_is_my_function():

有没有更优选的,确定的Python编码风格?

Coming from a C# background the naming convention for variables and method names are usually either camelCase or PascalCase:

// C# example
string thisIsMyVariable = "a"
public void ThisIsMyMethod()

In Python, I have seen the above but I have also seen underscores being used:

# python example
this_is_my_variable = 'a'
def this_is_my_function():

Is there a more preferable, definitive coding style for Python?


回答 0

请参阅Python PEP 8:函数和变量名称

函数名称应小写,必要时用下划线分隔单词,以提高可读性。

变量名遵循与函数名相同的约定。

仅在已经是主流样式(例如threading.py)的上下文中才允许使用blendCase,以保持向后兼容性。

See Python PEP 8: Function and Variable Names:

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

Variable names follow the same convention as function names.

mixedCase is allowed only in contexts where that’s already the prevailing style (e.g. threading.py), to retain backwards compatibility.


回答 1

Google Python样式指南》具有以下约定:

module_namepackage_nameClassNamemethod_nameExceptionNamefunction_nameGLOBAL_CONSTANT_NAMEglobal_var_nameinstance_var_namefunction_parameter_namelocal_var_name

类似的命名方案应适用于 CLASS_CONSTANT_NAME

The Google Python Style Guide has the following convention:

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


回答 2

大卫·Goodger(在“代码就像Pythonista” 在这里)描述了PEP 8项建议如下:

  • joined_lower 用于函数,方法,属性,变量

  • joined_lowerALL_CAPS常量

  • StudlyCaps 上课

  • camelCase 仅符合先前的约定

David Goodger (in “Code Like a Pythonista” here) describes the PEP 8 recommendations as follows:

  • joined_lower for functions, methods, attributes, variables

  • joined_lower or ALL_CAPS for constants

  • StudlyCaps for classes

  • camelCase only to conform to pre-existing conventions


回答 3

正如Python代码样式指南所承认的那样,

Python库的命名约定有些混乱,因此我们永远都无法做到这一点

请注意,这仅指Python的标准库。如果他们不能得到那个一致,那么就几乎是具有很大的希望通常附着到约定所有的 Python代码,不是吗?

因此,在这里的讨论中,我可以推断出,如果在过渡到Python时继续使用变量或函数的Java或C#命名惯例(例如清晰明确的命名规则),这并不是一个可怕的罪过。当然,请记住,最好遵守代码库/项目/团队的流行风格。正如《 Python风格指南》指出的那样,内部一致性最重要。

随意将我视为异端。:-)像OP一样,我也不是“ Pythonista”,无论如何也没有。

As the Style Guide for Python Code admits,

The naming conventions of Python’s library are a bit of a mess, so we’ll never get this completely consistent

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?

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.

Feel free to dismiss me as a heretic. :-) Like the OP, I’m not a “Pythonista”, not yet anyway.


回答 4

如其他答案所示,有PEP 8,但是PEP 8只是标准库的样式指南,在其中仅作为福音。PEP 8对于其他代码段最常见的偏差之一是变量命名,尤其是方法。尽管考虑到使用mixedCase的代码量很大,但没有单一的主导风格,如果要进行严格的普查,则可能最终会得到带有mixedCase的PEP 8版本。与PEP 8几乎没有其他偏差是很常见的。

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.


回答 5

如前所述,PEP 8表示可lower_case_with_underscores用于变量,方法和函数。

我更喜欢使用lower_case_with_underscores变量以及mixedCase方法和函数使代码更明确和可读。因此,遵循Python Zen的 “显式优于隐式”和“可读性”

As mentioned, PEP 8 says to use lower_case_with_underscores for variables, methods and functions.

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”


回答 6

@JohnTESlade回答的内容更进一步。Google的python样式指南提供了一些非常简洁的建议,

避免使用的名称

  • 单个字符名称(计数器或迭代器除外)
  • 任何程序包/模块名称中的破折号(-)
  • \__double_leading_and_trailing_underscore__ names (由Python保留)

命名约定

  • “内部”是指模块内部或类中受保护或私有的内部。
  • 在单个下划线(_)前面有一些支持来保护模块变量和函数(import * from中不包括)。在实例变量或方法前加双下划线(__)可以有效地使变量或方法对其类具有私有性(使用名称修饰)。
  • 将相关的类和顶级功能放到一个模块中。与Java不同,不需要将自己限制为每个模块一个类。
  • 使用CapWords类的名字,但lower_with_under.py对模块名称。尽管有许多命名的现有模块CapWords.py,但现在不建议这样做,因为当碰巧以一个类命名该模块时会造成混淆。(“等待-我写import StringIO还是写from StringIO import StringIO?”)

源自Guido建议的指南

further to what @JohnTESlade has answered. Google’s python style guide has some pretty neat recommendations,

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)

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).
  • 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.
  • Use CapWords for class names, but lower_with_under.py for module names. Although there are many existing modules named CapWords.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?”)

Guidelines derived from Guido’s Recommendations


回答 7

大多数python的人都喜欢使用下划线,但是自从5年前以来,即使我使用python,我仍然不喜欢它们。它们对我来说看起来很难看,但也许这就是我脑海中的所有Java。

我只是喜欢驼峰更好,因为它适合与类的命名方式更好,感觉更符合逻辑具有SomeClass.doSomething()SomeClass.do_something()。如果您在python中查看全局模块索引,则会发现这两者,这是因为它是随着时间的推移而增长的各种来源的库的集合,而不是由像Sun这样的公司开发的具有严格编码规则的库。我要说的底线是:使用任何您喜欢的更好的东西,这只是个人品味的问题。

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.

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.


回答 8

我个人尝试将CamelCase用于类,mixedCase方法和函数。变量通常用下划线分隔(当我记得时)。这样一来,我就可以一目了然地告诉我我到底在叫什么,而不是所有看起来都一样的东西。

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.


回答 9

有一篇关于此的论文:http : //www.cs.kent.edu/~jmaletic/papers/ICPC2010-CamelCaseUnderScoreClouds.pdf

TL; DR它说snake_case比camelCase更具可读性。这就是为什么现代语言在任何可能的地方使用(或应该使用)蛇的原因。

There is a paper about this: http://www.cs.kent.edu/~jmaletic/papers/ICPC2010-CamelCaseUnderScoreClouds.pdf

TL;DR It says that snake_case is more readable than camelCase. That’s why modern languages use (or should use) snake wherever they can.


回答 10

编码风格通常是组织内部政策/惯例标准的一部分,但我认为一般来说,all_lower_case_underscore_separator风格(也称为snake_case)在python中最为常见。

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.


回答 11

在以其他编程语言进行开发时,我个人使用Java的命名约定,因为它一致且易于遵循。这样,我就不会一直在努力使用哪些约定不应该成为我项目中最难的部分!

I personally use Java’s naming conventions when developing in other programming languages as it is consistent and easy to follow. That way I am not continuously struggling over what conventions to use which shouldn’t be the hardest part of my project!


回答 12

通常,遵循语言标准库中使用的约定。

Typically, one follow the conventions used in the language’s standard library.