What is the naming convention in Python for variable and function names?

Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:

// 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?


See 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

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.


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


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

  • 链接地址: http://www.djcxy.com/p/38272.html

    上一篇: ggplot2中标签文本条目中不同的字体和大小

    下一篇: Python中变量名和函数名的命名约定是什么?