Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:
// 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?
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.
further to what @JohnTESlade has answered. Google's python style guide has some pretty neat recommendations,
Names to Avoid
\__double_leading_and_trailing_underscore__ names
(reserved by Python)Naming Convention
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
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.
Typically, one follow the conventions used in the language's standard library.
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 conventionsAs mentioned, PEP 8 says to use
lower_case_with_underscores
for variables, methods and functions.I prefer using
lower_case_with_underscores
for variables andmixedCase
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"