1055

Coming from a C# background the naming convention for variables and methods 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 snake_case 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

15 Answers 15

1115

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.

24
  • 194
    PEP = Python Enhancement Proposal. Jul 31, 2009 at 21:18
  • 5
    The only problem with using underscores is that you can't select a variable or function name with a double click... you have to select the text manually. It is slightly annoying. Dec 7, 2013 at 14:13
  • 72
    One case for the underscored style is that you can use one-letter-words better. For (a rather silly) example, findMeAClass is perhaps uglier than find_me_a_class. Jun 28, 2014 at 21:16
  • 15
    I find that the convention of all-lowercase variable names is not suitable in scientific computing, where one often comes across well-known constants, tensors etc. that are denoted by capital letters.
    – andreasdr
    Oct 17, 2014 at 20:00
  • 24
    @rr PEP8 is a "Style Guide", and describes itself as a Convention, NOT a Standard. It also clearly explains the reasons for not always following those "rules".
    – The Tahaan
    Mar 13, 2015 at 8:28
1058

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

8
  • 51
    a) I love examples - thanks. b) Unattractive mixture of CamelCase and underscores? But: Being new to Python and its more flexible data model, I bet there's solid thinking behind Google's guide... Sep 10, 2012 at 14:29
  • 33
    @MatthewCornell mixing is not bad as long as you stick to it. It actually makes readability easier if you know that functions have underscores and classes don't.
    – Pithikos
    Sep 28, 2014 at 9:53
  • 2
    @MatthewCornell I wouldn't assume it has anything to do with python. Go actually enforces arbitrary standards of beauty and will fail to compile if you don't adhere to, for example, their curly brace convention. Essentially, it's a dice roll as to whether someone actually had a careful thought, or just really loved the way they do things. Jun 15, 2015 at 21:14
  • Would you consider a constant static attribute a GLOBAL_CONSTANT_NAME ? It's not exactly global as it's in the scope of the class.
    – James T.
    Jan 23, 2018 at 22:19
  • then walks in property ... perhaps it's a matter of what the item is pretending to be, rather than what it actually is
    – joel
    Oct 8, 2019 at 19:32
297

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

6
  • 3
    +1 visual examples. Though I couldn't see where PEP8 suggests joined_lower for constants, only "all capital letters with underscores separating words". Curious also about the new enum feature.
    – Bob Stein
    Jan 19, 2015 at 13:11
  • 3
    StudlyCaps for classes is a great universal rule for classes in almost all languages. Then why are some python built-in classes (such as datetime.datetime doesn't follow this convention? Jan 12, 2017 at 10:52
  • 5
    @PrahladYeri: Unfortunately, unittest.TestCase.assertEqual and friends don't follow the snake_case convention, either. The truth is that parts of the Python standard library were developed before the conventions had solidified, and we are now stuck with them.
    – wchargin
    Mar 18, 2017 at 14:29
  • 6
    CamelCase is confusing because some people say it's "camelCase" (also known as "mixedCase") and some people say it's "CamelCase" (also known as "StudlyCaps"). For example, the PEP mentions "CamelCase" while you mention "camelCase".
    – Pro Q
    Jun 26, 2017 at 14:55
  • your here-link is dead, maybe it should be replaced by something like david.goodger.org/projects/pycon/2007/idiomatic
    – Wolf
    Oct 15, 2019 at 9:37
57

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.

38

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"

3
  • 5
    +1 I switch those two (I use mixedCase for variables), but having everything more distinct like that helps make it immediately obvious what you're dealing with, especially since you can pass around functions. Jul 12, 2009 at 17:51
  • 7
    Though "Readability" is highly subjective. I find methods with underscore more readable.
    – Pithikos
    Sep 30, 2014 at 15:24
  • Your preference was my initial intuition coming from a lot of years of Java development. I like using _ for variables, but from eyes, it just looks a little funny to me for functions and methods. Jul 13, 2016 at 22:24
35

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.

2
  • 15
    This may have been true in '08 when this was answered, but nowadays almost all major libraries use PEP 8 naming conventions. Oct 28, 2015 at 2:04
  • 2
    @ThaneBrimhall In 2022, I am kicking everyone's butt who hands me newly written non-PEP 8 conformant code to review.
    – Cerno
    Jan 13, 2022 at 13:26
34

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 enter image description here

29

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.

3
  • 14
    I'm coming from a Java background, and I find underscores verbose and unattractive, with only the latter being opinion. Naming is in some respects a balance between readability and brevity. Unix goes too far, but its en.wikipedia.org/wiki/Domain-specific_language is limited. CamelCase is readable due to the caps, but has no extra chars. 2c Sep 10, 2012 at 14:29
  • 4
    For me underscores are attractive in functions/methods since I see every underscore as a separator for a virtual (in my head) namespace. That way I can easily know how to name my new functions/methods: make_xpath_predicate, make_xpath_expr, make_html_header, make_html_footer
    – Pithikos
    Sep 28, 2014 at 9:59
  • 10
    You don't (typically) call SomeClass.doSomething() (static methods are generally rare) you usually call an_instance.do_something()
    – Dave
    Sep 26, 2018 at 23:40
21

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.

5
  • 15
    Camel case starts with a lowercase letter IIRC like "camelCase".
    – UnkwnTech
    Oct 3, 2008 at 11:51
  • 12
    I think crystalattice had it right - at least, his usage is consistent with the usage in the PEP8 (CamelCase and mixedCase).
    – Jarrett
    Oct 4, 2012 at 19:34
  • 1
    @UnkwnTech The term for FirstLetterUpper is sometimes called PascalCase Jun 3, 2019 at 23:56
  • CamelCase or camelCase ? justWondering. Jan 22, 2020 at 19:29
  • 2
    @SumitPokhrel it is PascalCase and camelCase, AFAIK. May 5, 2022 at 14:02
18

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.

2
  • 13
    Interestingly, it also says, "The results of this study might not necessarily apply to identifiers embedded in source code. It is entirely possible that camel- cased identifiers might act as a better gestalt element when embedded inside programming constructs."
    – rob3c
    Oct 2, 2016 at 3:36
  • 1
    I think a lot of the reason behind using snake_case was that many system used to capitalize everything, therefore CamelCase becomes CAMELCASE. Now that is no longer the case. Personally, I like to use snake_case for the internal, low-level, system stuff, and keep mixedCase / CamelCase for the interfaces. I don't know how these people do research, my eye-tracking is definitely the fastest for short CamelCase and mixedCase names. Oct 7, 2021 at 15:21
7

Whether or not being in class or out of class:

A variable and function are lowercase as shown below:

name = "John"
def display(name):
    print("John")

And if they're more than one word, they're separated with underscore "_" as shown below:

first_name = "John"
def display_first_name(first_name):
    print(first_name)

And, if a variable is a constant, it's uppercase as shown below:

FIRST_NAME = "John"
5

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.

2

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!

1
  • 2
    I somewhat agree. If language X is only a small amount of the project, the context switch of how to format text can be a burden. The main hiccup is that libraries will have calls in one style (library_function(my_arg)).
    – Lan
    Apr 22, 2020 at 1:51
2

Lenin has told... I'm from Java/C# world too. And SQL as well. Scrutinized myself in attempts to find first sight understandable examples of complex constructions like list in the dictionary of lists where everything is an object. As for me - camelCase or their variants should become standard for any language. Underscores should be preserved for complex sentences.

0
0

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.