Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 528
Ray Avatar asked Oct 01 '08 21:10

Ray


People also ask

What is the naming convention for variables and functions?

Function and Class Naming conventions An important aspect of naming is to ensure your classes, functions, and variables can be distinguished from each other. For example, one could use Camelcase and Pascalcase for functions and classes respectively, while reserving Snakecase or Hungarian notation for variable names.


2 Answers

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.

like image 79
S.Lott Avatar answered Sep 28 '22 00:09

S.Lott


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

like image 37
JohnTESlade Avatar answered Sep 28 '22 01:09

JohnTESlade