13

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?

5
  • 3
    If you've already looked at PEP 8, there's probably not much else that's widely accepted as a standard...
    – David Z
    May 12, 2010 at 0:03
  • @David: Thanks, I'll follow up PEP 8 then. @Fuzzy lollipop: Why? May 12, 2010 at 0:11
  • 2
    this is a quote "Nothing worse than a character that looks like a sequence of spaces but isn't, that look like a DIFFERENT number of spaces depending on your display settings, and that you may not even be able to type without reconfiguring your editor! Any editor lets you type spaces last time I checked." That pretty much sums it up.
    – user177800
    May 12, 2010 at 1:22
  • 1
    @Oscar Carballal: No matter what the space zealots say, tabs are not evil (unless mixed with spaces, which basically everyone agrees is evil). There are perfectly legitimate, rational reasons to like tabs. However, if you plan on working with other people (virtually a given if you are talking about an open source project), you will need to switch to using all spaces, just as a matter of pragmatism.
    – John Y
    May 12, 2010 at 1:51
  • I've used tabs for many years; no, they're not evil. The Python 3 change that throws an error when mixing tabs and spaces, however, is very evil: it means you have to change your editor's configuration to edit different codebases, for academic and in practice no benefit. May 12, 2010 at 3:18

3 Answers 3

21

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.

2
2

1.- Most everyone has a 16:9 or 16:10 monitor now days. Even if they don't have a wide-screen they have lots of pixels, 80 cols isn't a big practical deal breaker like it was when everyone was hacking at the command line in a remote terminal window on a 4:3 monitor at 320 X 240. I usually end the line when it gets too long, which is subjective. I am at 2048 X 1152 on a 23" Monitor X 2.

2.- Single quotes by default so you don't have to escape Double quotes, Double quotes when you need to embed single quotes, and Triple quotes for strings with embedded newlines.

3.- Put them at the top of the file, sometimes you put them in the main function if they aren't needed globally to the module.

4.- It is a common idiom to rename some modules. A good example is the following.

try:
    # for Python 2.6.x
    import json
except ImportError:
    # for previous Pythons
    try:
        import simplejson as json
    except ImportError:
        sys.exit('easy_install simplejson')

but the preferred way to import just a class or function is from module import xxx with the optional as yyy if needed

5.- Always use SPACES! 2 or 4 as long as no TABS

6.- Classes should up UpperCaseCamelStyle, variables are lowercase sometimes lowerCamelCase or sometimes all_lowecase_separated_by_underscores, as are function names. "Constants" should be ALL_UPPER_CASE_SEPARATED_BY_UNDERSCORES

When in doubt refer to the PEP 8, the Python source, existing conventions in a code base. But the most import thing is to be internally consistent as possible. All Python code should look like it was written by the same person when ever possible.

3
  • 80 columns lets you code on phone/handheld, and when I need to work on something via terminal (ie: X server blows up), it's a lot easier because 80 columns always fits in it. Also all my screens fit two 80 column windows side by side, and I usually have 4+ sources open at once for cross referencing. If you make things too vertical it's harder to follow... I suppose it doesn't really matter since you can use an auto formatter... May 12, 2010 at 3:18
  • 3
    +1 for rare common sense about 80-column wrapping. The PEP8 advice to wrap at 80 columns was dated even when it was written, and does nothing but mangle code. Wrap to 120 columns or so. If anyone's really still editing code in 80x25, they'll live. May 12, 2010 at 3:22
  • 1
    -1 for 80-column wrapping commentary. It's not a matter of it being dated, as much as it's a matter of utilizing screen space most efficiently since screens are still being made horizontally long. This makes 80 characters easy to align 4 columns of code on a typical screen for me. Seeing code that's not kept at 80 columns is very difficult to look at in this environment. As for the original commentary about it being difficult to keep up with: it's easier to not worry about it, then run a script like autopep8 on it when you're ready to maintain it.
    – Bobby
    Jan 9, 2016 at 23:30
1

Since I'm really crazy about "styling" I'll write down the guidelines that I currently use in a near 8k SLOC project with about 35 files, most of it matches PEP8.

  1. PEP8 says 79(WTF?), I go with 80 and I'm used to it now. Less eye movement after all!

  2. Docstrings and stuff that spans multiple lines in '''. Everything else in ''. Also I don't like double quotes, I only use single quotes all the time... guess that's because I came form the JavaScript corner, where it's just easier too use '', because that way you don't have to escape all the HTML stuff :O

  3. At the head, built-in before custom application code. But I also go with a "fail early" approach, so if there's something that's version depended(GTK for example) I'd import that first.

  4. Depends, most of the times I go with import foo and from foo import, but there a certain cases(e.G. the name is already defined by another import) were I use from foo import bar as bla too.

  5. 4 Spaces. Period. If you really want to use tabs, make sure to convert them to spaces before committing when working with SCM. BUT NEVER(!) MIX TABS AND SPACES!!! It can AND WILL introduce horrible bugs.

  6. some_method or foo_function, a CONSTANT, MyClass.

Also you can argue about indentation in cases where a method call or something spans multiple lines, and you can argue about which line continuation style you will use. Either surround everything with () or do the \ at the end of the line thingy. I do the latter, and I also place operators and other stuff at the start of the next line.

# always insert a newline after a wrapped one
from bla import foo, test, goo, \
                another_thing

def some_method_thats_too_long_for_80_columns(foo_argument, bar_argument, bla_argument,
                                              baz_argument):

    do_something(test, bla, baz)

    value = 123 * foo + ten \
            - bla

    if test > 20 \
       and x < 4:

        test_something()

    elif foo > 7 \
         and bla == 2 \
         or me == blaaaaaa:

        test_the_megamoth()

Also I have some guidelines for comparison operations, I always use is(not) to check against None True False and I never do an implicit boolean comparison like if foo:, I always do if foo is True:, dynamic typing is nice but in some cases I just want to be sure that the thing does the right thing!

Another thing that I do is to never use empty strings! They are in a constants file, in the rest of the code I have stuff like username == UNSET_USERNAME or label = UNSET_LABEL it's just more descriptive that way!

I also have some strict whitespace guidelines and other crazy stuff, but I like it(because I'm crazy about it), I even wrote a script which checks my code:
http://github.com/BonsaiDen/Atarashii/blob/master/checkstyle

WARNING(!): It will hurt your feelings! Even more than JSLint does...

But that's just my 2 cents.

1
  • my 2048X1152 monitor leaves plenty of space for diff markup at 180 columns at 12 points!
    – user177800
    Jan 9, 2016 at 23:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.