Search code examples
pythoncoding-stylenaming-conventionsindentationcolumn-width

Common coding style for Python?


I'm pretty new to Python, and I want to develop my first serious open source project. I want to ask what is the common coding style for python projects. I'll put also what I'm doing right now.

1.- What is the most widely used column width? (the eternal question)
I'm currently sticking to 80 columns (and it's a pain!)

2.- What quotes to use? (I've seen everything and PEP 8 does not mention anything clear)
I'm using single quotes for everything but docstrings, which use triple double quotes.

3.- Where do I put my imports?
I'm putting them at file header in this order.

import sys
import -rest of python modules needed-

import whatever
import -rest of application modules-

<code here>

4.- Can I use "import whatever.function as blah"?
I saw some documents that disregard doing this.

5.- Tabs or spaces for indenting?
Currently using 4 spaces tabs.

6.- Variable naming style? I'm using lowercase for everything but classes, which I put in camelCase.

Anything you would recommend?


Solution

  • PEP 8 is pretty much "the root" of all common style guides.

    Google's Python style guide has some parts that are quite well thought of, but others are idiosyncratic (the two-space indents instead of the popular four-space ones, and the CamelCase style for functions and methods instead of the camel_case style, are pretty major idiosyncrasies).

    On to your specific questions:

    1.- What is the most widely used column width? (the eternal question) I'm currently sticking to 80 columns (and it's a pain!)

    80 columns is most popular

    2.- What quotes to use? (I've seen everything and PEP 8 does not mention anything clear) I'm using single quotes for everything but docstrings, which use triple double quotes.

    I prefer the style you're using, but even Google was not able to reach a consensus about this:-(

    3.- Where do I put my imports? I'm putting them at file header in this order.

    import sys import -rest of python modules needed-

    import whatever import -rest of application modules-

    Yes, excellent choice, and popular too.

    4.- Can I use "import whatever.function as blah"? I saw some documents that disregard doing this.

    I strongly recommend you always import modules -- not specific names from inside a module. This is not just style -- there are strong advantages e.g. in testability in doing that. The as clause is fine, to shorten a module's name or avoid clashes.

    5.- Tabs or spaces for indenting? Currently using 4 spaces tabs.

    Overwhelmingly most popular.

    6.- Variable naming style? I'm using lowercase for everything but classes, which I put in camelCase.

    Almost everybody names classes with uppercase initial and constants with all-uppercase.