views:

242

answers:

3

Hi,

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?

+10  A: 

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.

Alex Martelli
Thanks! I'll follow your advice on importing modules instead of functions :)
Oscar Carballal
+3  A: 

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.

fuzzy lollipop
Thanks, good example on renaming modules :D
Oscar Carballal
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...
Longpoke
+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.
Glenn Maynard
+1  A: 

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.

Ivo Wetzel
79 leaves an extra column for diff markup.
Longpoke