ChatGPT解决这个技术问题 Extra ChatGPT

What is the naming convention in Python for variable and function?

Coming from a C# background the naming convention for variables and method names 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 underscores being used:

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

Is there a more preferable, definitive coding style for Python?


C
Community

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.


PEP = Python Enhancement Proposal.
@RickyRobinson What brain-dead code editor are you using, that doesn't know that underscore continues a word? Lots of free ones that do. I use Notepad++, if an IDE isn't available. For that, can download a template for python editing. (Others can recommend even more useful free downloads.)
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.
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.
@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".
B
Boris Verkhovskiy

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


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...
@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.
@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.
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.
then walks in property ... perhaps it's a matter of what the item is pretending to be, rather than what it actually is
u
unmounted

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


+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.
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?
@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.
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".
your here-link is dead, maybe it should be replaced by something like david.goodger.org/projects/pycon/2007/idiomatic
J
Jonik

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.


c
claytron

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"


+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.
Though "Readability" is highly subjective. I find methods with underscore more readable.
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.
T
Thomas Wouters

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.


This may have been true in '08 when this was answered, but nowadays almost all major libraries use PEP 8 naming conventions.
@ThaneBrimhall In 2022, I am kicking everyone's butt who hands me newly written non-PEP 8 conformant code to review.
S
Sufiyan Ghori

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?")

https://i.stack.imgur.com/uBr10.png


c
cxrodgers

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.


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
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
You don't (typically) call SomeClass.doSomething() (static methods are generally rare) you usually call an_instance.do_something()
c
crystalattice

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.


Camel case starts with a lowercase letter IIRC like "camelCase".
I think crystalattice had it right - at least, his usage is consistent with the usage in the PEP8 (CamelCase and mixedCase).
@UnkwnTech The term for FirstLetterUpper is sometimes called PascalCase
CamelCase or camelCase ? justWondering.
@SumitPokhrel it is PascalCase and camelCase, AFAIK.
a
alebian

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.


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."
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.
S
Shawn Mehan

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.


b
bradylange

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!


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)).
v
vic123

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.


K
Kai - Kazuya Ito

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"

y
yfeldblum

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