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?
16 Answers 16
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.
-
206PEP = Python Enhancement Proposal.Peter Mortensen– Peter Mortensen2009年07月31日 21:18:48 +00:00Commented Jul 31, 2009 at 21:18
-
12The 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.Ricky Robinson– Ricky Robinson2013年12月07日 14:13:59 +00:00Commented Dec 7, 2013 at 14:13
-
77One case for the underscored style is that you can use one-letter-words better. For (a rather silly) example,
findMeAClass
is perhaps uglier thanfind_me_a_class
.heltonbiker– heltonbiker2014年06月28日 21:16:49 +00:00Commented Jun 28, 2014 at 21:16 -
20I 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– andreasdr2014年10月17日 20:00:06 +00:00Commented Oct 17, 2014 at 20:00
-
29@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– The Tahaan2015年03月13日 08:28:43 +00:00Commented Mar 13, 2015 at 8:28
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
-
57a) 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...Matthew Cornell– Matthew Cornell2012年09月10日 14:29:30 +00:00Commented Sep 10, 2012 at 14:29
-
35@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– Pithikos2014年09月28日 09:53:49 +00:00Commented 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.Parthian Shot– Parthian Shot2015年06月15日 21:14:04 +00:00Commented 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.– James T.2018年01月23日 22:19:55 +00:00Commented Jan 23, 2018 at 22:19
-
1Just why... Why?! Why not C# style, for example? It looks so... weird... everything is
lowercase
+underscores
regardless access modifier, parameter vs variable and also making them longer ifmixedCase
, for example... I don't like current popular Python name convention... The code is so unreadable with such style and big project...Serious Angel– Serious Angel2021年04月28日 16:18:07 +00:00Commented Apr 28, 2021 at 16:18
David Goodger (in "Code Like a Pythonista" here) describes the PEP 8 recommendations as follows:
joined_lower
for functions, methods, attributes, variablesjoined_lower
orALL_CAPS
for constantsStudlyCaps
for classescamelCase
only to conform to pre-existing conventions
-
4
-
3
StudlyCaps for classes
is a great universal rule for classes in almost all languages. Then why are some python built-in classes (such asdatetime.datetime
doesn't follow this convention?Prahlad Yeri– Prahlad Yeri2017年01月12日 10:52:05 +00:00Commented Jan 12, 2017 at 10:52 -
6@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– wchargin2017年03月18日 14:29:00 +00:00Commented Mar 18, 2017 at 14:29 -
7CamelCase 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– Pro Q2017年06月26日 14:55:53 +00:00Commented 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/idiomaticWolf– Wolf2019年10月15日 09:37:47 +00:00Commented Oct 15, 2019 at 9:37
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.
-
While this answer is somewhat old, and possibly from a more permissive age, I consider that the broadly representative opinion of the vast majority of Python programmers today do regard it as a horrible sin to use other foreign language conventions with Python. Time has shown that it's pretty easy to get style rules across many libraries consistent regardless of the early variations in the standard library, hence the existence of tools like Black which help all code read the same for greater efficiency.NeilG– NeilG2024年05月07日 05:22:49 +00:00Commented May 7, 2024 at 5:22
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"
-
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.Xiong Chiamiov– Xiong Chiamiov2009年07月12日 17:51:02 +00:00Commented Jul 12, 2009 at 17:51
-
7Though "Readability" is highly subjective. I find methods with underscore more readable.Pithikos– Pithikos2014年09月30日 15:24:23 +00:00Commented 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.Michael Szczepaniak– Michael Szczepaniak2016年07月13日 22:24:15 +00:00Commented Jul 13, 2016 at 22:24
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, butlower_with_under.py
for module names. Although there are many existing modules namedCapWords.py
, this is now discouraged because it's confusing when the module happens to be named after a class. ("wait -- did I writeimport StringIO
orfrom StringIO import StringIO
?")
Guidelines derived from Guido's Recommendations enter image description here
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.
-
17This may have been true in '08 when this was answered, but nowadays almost all major libraries use PEP 8 naming conventions.Thane Brimhall– Thane Brimhall2015年10月28日 02:04:58 +00:00Commented Oct 28, 2015 at 2:04
-
4@ThaneBrimhall In 2022, I am kicking everyone's butt who hands me newly written non-PEP 8 conformant code to review.Cerno– Cerno2022年01月13日 13:26:41 +00:00Commented Jan 13, 2022 at 13:26
-
This answer is like a little PEeP into history that has now long gone.NeilG– NeilG2024年05月07日 05:25:22 +00:00Commented May 7, 2024 at 5:25
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.
-
14I'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. 2cMatthew Cornell– Matthew Cornell2012年09月10日 14:29:13 +00:00Commented Sep 10, 2012 at 14:29
-
4For 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– Pithikos2014年09月28日 09:59:20 +00:00Commented Sep 28, 2014 at 9:59 -
12You don't (typically) call
SomeClass.doSomething()
(static methods are generally rare) you usually callan_instance.do_something()
Dave– Dave2018年09月26日 23:40:04 +00:00Commented Sep 26, 2018 at 23:40 -
Yes, it's all the Java in your head ;-)NeilG– NeilG2024年05月07日 05:23:45 +00:00Commented May 7, 2024 at 5:23
-
It's beyond comprehension that anyone could prefer the verbosity and aesthetic violation of underscores everywhere. But I swear if I see one more person write camelCase with an initial uppercase C - can't you see a camel's humps are in the middle?gknicker– gknicker2024年12月06日 00:57:42 +00:00Commented Dec 6, 2024 at 0:57
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.
-
16Camel case starts with a lowercase letter IIRC like "camelCase".UnkwnTech– UnkwnTech2008年10月03日 11:51:24 +00:00Commented Oct 3, 2008 at 11:51
-
12I think crystalattice had it right - at least, his usage is consistent with the usage in the PEP8 (CamelCase and mixedCase).Jarrett– Jarrett2012年10月04日 19:34:33 +00:00Commented Oct 4, 2012 at 19:34
-
1@UnkwnTech The term for FirstLetterUpper is sometimes called PascalCaseSurpriseDog– SurpriseDog2019年06月03日 23:56:00 +00:00Commented Jun 3, 2019 at 23:56
-
CamelCase or camelCase ? justWondering.Sumit Pokhrel– Sumit Pokhrel2020年01月22日 19:29:05 +00:00Commented Jan 22, 2020 at 19:29
-
3@SumitPokhrel it is PascalCase and camelCase, AFAIK.Alejandro QA– Alejandro QA2022年05月05日 14:02:44 +00:00Commented May 5, 2022 at 14:02
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.
-
15Interestingly, 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– rob3c2016年10月02日 03:36:39 +00:00Commented Oct 2, 2016 at 3:36
-
1I 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.Justin Zhang– Justin Zhang2021年10月07日 15:21:23 +00:00Commented Oct 7, 2021 at 15:21
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"
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.
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.
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!
-
2I 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– Lan2020年04月22日 01:51:17 +00:00Commented Apr 22, 2020 at 1:51
PEP 8 is a guideline, not a law. It is an option on top of Python, not part of the official language. If everybody uses the same style, this would be preferred in a bigger company.
All my Python programs at home run perfect with camelCaseNames, I will not change this unless people can prove my code is runner slower or has wrong behavior. However, on my job they want designers to follow the same rules and therefore have chosen for PEP 8 with a set of additional rules. This does not mean they use autopep8, there are many tools to be PEP8 compliant with small variations like black, flake8, autopep8.
The tools that improve code to be PEP8 compliant are mainly based on opinion management. So, if people use words like "Must have", "Should have", "Shall have", these should be replaced by "could have". I would ask your company their preference.
Next to PEP8, I could recommend pylint and mypy, those tools really find issues and showstoppers in your code.
Typically, one follow the conventions used in the language's standard library.
Explore related questions
See similar questions with these tags.