What is the naming convention in Python for variables and functions?
Asked Answered
E

15

1084

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?

Eleonoreeleoptene answered 1/10, 2008 at 21:1 Comment(0)
P
1140

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.

Purse answered 1/10, 2008 at 21:5 Comment(24)
PEP = Python Enhancement Proposal.Ghetto
How about function argument names (in particular, for keyword arguments)? PEP 8 isn't explicit about them. I assume lowercase with underscores for them too. Or is lowercase without underscores preferred?Dowell
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.Zilvia
I threw together a sed command to convert mixedCase (but not CapitalWords) to lower_case_with_underscores in case anyone finds that useful, e.g. to do it the way you like but then release it in the PEP 8 preferred way: stackoverflow.com/questions/23607374Harbison
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.Measureless
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.Khajeh
note that the guideline says "as necessary to improve readability". So you can also just concatenate without the underscore if it looks better. So: lower_case_with_underscores, could also be, lowercase_with_underscores and utc_from_timestamp could be utcfromtimestampGleason
Standards are there to follow them, not question them. I don't hold people who say "this standard sucks. I'll make my own standard" in very high regard. That being said, the rule: mixedCase is allowed only in contexts where that's already the prevailing style makes this whole rule utterly pointless. What kind of standard tells you to "do X... unless you don't" ...?Backblocks
@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".Potoroo
@Khajeh On the one hand, you're right, but on the other hand every naming convention has the idea of a "default" case convention. So, camelCase would have you capitalize the "e" for Euler's number. At that point you could argue that it's no longer acting as an alphabetical character, and is instead behaving as its own symbol. Which, incidentally, is why such symbols tend to be put in italics or otherwise offset (e.g. the cursive L for Laplace transform).Auburta
This might be slightly off topic because I am concerned with the naming convention for classes, BUT: when people say that the style convention for classes is UpperCase, does that mean this is only true for the definitions but also for class instances?Storekeeper
I don't see the benefit of following PEP 8, while Javascript, php, swift, java and other languages mostly use camelCase for method. You shouldn't change your coding style for each language, that's stupid. In general, camelCase is the better choice whathecode.wordpress.com/2011/02/10/…Basil
Not so fast, @TomSawyer! The article linked from the blog found that camel case resulted in more more accuracy, but finding "identifiers written in the camel case style took 0.42 seconds more time." But training in camel case does make us faster in that style. (See pp. 7-8 of <the pdf>. So camel case is slower over all, but safer when there are look-alike variables-- and this was a very narrow experimental set-up, as the authors point out.Calista
@Calista I didn't say anything about which one is faster in typing. All i wanted to say is changing coding style for each language is a stupid thing. Especially in the Json era, camelCase is everywhere google.github.io/styleguide/jsoncstyleguide.xmlBasil
Actually wasn't about typing, it was about spotting the identifiers among other words. But you're right, changing styles is costly no matter which direction you go.Calista
Why ignore the followup? whathecode.wordpress.com/2013/02/16/… So the first study found that reading camel case takes 13.5% more time while the second one found it takes 20% more time. Camel case should be renamed "snail case"!Bobstay
Worth noting, from the same document in a section called "A Foolish Consistency is the Hobgoblin of Little Minds": "However, know when to be inconsistent -- sometimes style guide recommendations just aren't applicable. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don't hesitate to ask!"Obstetrics
@Yablargo switch to Dvorak and you will find that lower_case_names are much faster to type as the underscore key "_" is on the keyboard's home row.Autotruck
What is your recommendation when you want a variable that is a reserved keyword such as type ? typee ttype type typeWorthy
@Worthy Use type_ if it's already reserved. _type would be for protected variable names.Lema
mixedCase is rather standard now, underscore takes too much placeFlori
The "underscore separated words" are called snake_case anywayImpious
"as necessary" 😑 in practice this means guessing what the author thought was looking niceOiler
@ParthianShot the beauty of Python is that you can use a cursive for Euler's number or curly 'ℒ'' for lagrangian in your code. Whether that's a good idea, is a different question. Especially the first example removes any ambiguity.Undersized
D
1085

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

Doublepark answered 7/12, 2011 at 22:44 Comment(8)
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...Castleman
@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.Alphonsoalphonsus
@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.Auburta
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.Fabrianna
then walks in property ... perhaps it's a matter of what the item is pretending to be, rather than what it actually isCopland
I don't know whether this should be a separate question but one convention not mentioned here is how to name function arguments. I think it fits within the scope of this question so it would be nice if this was also answered here. For example if something takes generic lists what should it be. I think it is not recommended to use for example list or dict as the name of the function argument since these already exist. What should be used instead? ls, dc?Cauley
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...Unskillful
What about file and folder naming?Charmeuse
P
303

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

Protist answered 2/10, 2008 at 3:53 Comment(6)
+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.Manille
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?Henbit
@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.Clovah
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".Bordie
your here-link is dead, maybe it should be replaced by something like david.goodger.org/projects/pycon/2007/idiomaticToon
What if API returns response with camelCase, but your python code converts it to some object with snake_case attributes? Is it OK? IMHO, it should keep case of API response.Rokach
F
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.

Fierro answered 25/4, 2010 at 11:23 Comment(0)
L
37

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"

Lakeshialakey answered 5/11, 2008 at 2:51 Comment(3)
+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.Menhir
Though "Readability" is highly subjective. I find methods with underscore more readable.Alphonsoalphonsus
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.Gardy
F
34

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.

Fluviatile answered 1/10, 2008 at 21:12 Comment(2)
This may have been true in '08 when this was answered, but nowadays almost all major libraries use PEP 8 naming conventions.Torrid
@ThaneBrimhall In 2022, I am kicking everyone's butt who hands me newly written non-PEP 8 conformant code to review.Grimmett
L
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

Li answered 20/6, 2018 at 23:49 Comment(0)
M
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.

Martins answered 1/10, 2008 at 21:16 Comment(3)
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. 2cCastleman
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_footerAlphonsoalphonsus
You don't (typically) call SomeClass.doSomething() (static methods are generally rare) you usually call an_instance.do_something()Hardheaded
A
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.

Abuse answered 2/10, 2008 at 3:24 Comment(5)
Camel case starts with a lowercase letter IIRC like "camelCase".Twila
I think crystalattice had it right - at least, his usage is consistent with the usage in the PEP8 (CamelCase and mixedCase).Flamen
@Twila The term for FirstLetterUpper is sometimes called PascalCaseAutotruck
CamelCase or camelCase ? justWondering.Arsenite
@SumitPokhrel it is PascalCase and camelCase, AFAIK.Leucocyte
D
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.

Derringdo answered 9/5, 2016 at 16:20 Comment(2)
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."Conferva
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.Elixir
H
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"
Heuser answered 13/6, 2022 at 13:8 Comment(0)
A
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.

Airliah answered 1/10, 2008 at 21:8 Comment(0)
M
1

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!

Mazurek answered 22/8, 2019 at 3:37 Comment(1)
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)).Kopans
G
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.

Gump answered 27/8, 2021 at 20:3 Comment(0)
B
-1

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

Brawny answered 2/10, 2008 at 3:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.