Coder Perfect

What is the Python naming convention for variables and functions?


Coming from a C# background, I’m used to camelCase or PascalCase naming conventions for variables and methods:

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

I’ve seen the above in Python, but I’ve also seen underscores used:

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

Is there a preferred, unmistakable coding style for Python?

Asked by Ray

Solution #1

See Python PEP 8: Function and Variable Names for more information.

Answered by S.Lott

Solution #2

The following is a convention from the Google Python Style Guide:

A CLASS CONSTANT NAME should be named in a same manner.

Answered by JohnTESlade

Solution #3

The PEP 8 recommendations are described as follows by David Goodger (in “Code Like a Pythonista” here):

Answered by unmounted

Solution #4

As the Python Code Style Guide concedes,

It’s important to note that this only refers to Python’s standard library. If they can’t get that consistent, what chance do they have of having a universally accepted convention for all Python code?

Based on that and the discussion here, I believe that continuing to use the (clear and well-established) naming standards for variables and functions in Java or C# while moving to Python is not a terrible sin. Keeping in mind, of course, that whatever the prevalent style for a codebase, project, or team happens to be, it’s better to follow it. Internal consistency is very important, as the Python Style Guide points out.

You are free to label me a heretic. 🙂 I, like the OP, am not a “Pythonista,” at least not yet.

Answered by Jonik

Solution #5

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

It makes the code more plain and readable to use lower case with underscores for variables and mixedCase for methods and functions. As a result, according to the Zen of Python’s “explicit is better than implicit” and “readability counts” principles.

Answered by claytron

Post is based on