1127

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?

cobrexus
4,8545 gold badges24 silver badges51 bronze badges
asked Oct 1, 2008 at 21:01
0

16 Answers 16

1176

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.

answered Oct 1, 2008 at 21:05
27
  • 206
    PEP = Python Enhancement Proposal. Commented Jul 31, 2009 at 21:18
  • 12
    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. Commented Dec 7, 2013 at 14:13
  • 77
    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. Commented Jun 28, 2014 at 21:16
  • 20
    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. Commented 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". Commented Mar 13, 2015 at 8:28
1128

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

answered Dec 7, 2011 at 22:44
14
  • 57
    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... Commented 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. Commented 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. Commented 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. Commented Jan 23, 2018 at 22:19
  • 1
    Just 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 if mixedCase, for example... I don't like current popular Python name convention... The code is so unreadable with such style and big project... Commented Apr 28, 2021 at 16:18
314

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

NeilG
4,1182 gold badges29 silver badges39 bronze badges
answered Oct 2, 2008 at 3:53
7
  • 4
    +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. Commented 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? Commented 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. Commented Mar 18, 2017 at 14:29
  • 7
    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". Commented 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 Commented 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.

answered Apr 25, 2010 at 11:23
1
  • 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. Commented May 7, 2024 at 5:22
39

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"

answered Nov 5, 2008 at 2:51
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. Commented Jul 12, 2009 at 17:51
  • 7
    Though "Readability" is highly subjective. I find methods with underscore more readable. Commented 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. Commented Jul 13, 2016 at 22:24
37

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

InSync
12k5 gold badges21 silver badges58 bronze badges
answered Jun 20, 2018 at 23:49
33

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.

answered Oct 1, 2008 at 21:12
3
  • 17
    This may have been true in '08 when this was answered, but nowadays almost all major libraries use PEP 8 naming conventions. Commented 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. Commented Jan 13, 2022 at 13:26
  • This answer is like a little PEeP into history that has now long gone. Commented May 7, 2024 at 5:25
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.

cxrodgers
4,7372 gold badges26 silver badges33 bronze badges
answered Oct 1, 2008 at 21:16
5
  • 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 Commented 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 Commented Sep 28, 2014 at 9:59
  • 12
    You don't (typically) call SomeClass.doSomething() (static methods are generally rare) you usually call an_instance.do_something() Commented Sep 26, 2018 at 23:40
  • Yes, it's all the Java in your head ;-) Commented 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? Commented Dec 6, 2024 at 0:57
20

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.

answered Oct 2, 2008 at 3:24
5
  • 16
    Camel case starts with a lowercase letter IIRC like "camelCase". Commented 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). Commented Oct 4, 2012 at 19:34
  • 1
    @UnkwnTech The term for FirstLetterUpper is sometimes called PascalCase Commented Jun 3, 2019 at 23:56
  • CamelCase or camelCase ? justWondering. Commented Jan 22, 2020 at 19:29
  • 3
    @SumitPokhrel it is PascalCase and camelCase, AFAIK. Commented May 5, 2022 at 14:02
16

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.

answered May 9, 2016 at 16:20
2
  • 15
    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." Commented 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. Commented Oct 7, 2021 at 15:21
6

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"
Henry Ecker
35.8k19 gold badges48 silver badges67 bronze badges
answered Jun 13, 2022 at 13:08
4

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.

Shawn Mehan
4,58810 gold badges33 silver badges51 bronze badges
answered Oct 1, 2008 at 21:08
1

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.

answered Aug 27, 2021 at 20:03
0
0

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!

answered Aug 22, 2019 at 3:37
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)). Commented Apr 22, 2020 at 1:51
-1

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.

answered May 1, 2024 at 9:37
-3

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

answered Oct 2, 2008 at 3:55

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.