Coding Style

Programs must be written for people to read, and only incidentally for machines to execute. -- Abelson & Sussman, Structure and Interpretation of Computer Programs

Python

Keep in mind:

  • Never do:

    from module import *
  • Don't use mutable object as default parameter like this:

    def func(l=[]):
        pass

    Use it this way:

    def func(l=None):
        if l is None:
            l = []
  • When using string formatting operations like formatString % values you should always use a tuple if you're using non-mapping values. This is to avoid unexpected behavior when you think you're passing in a single value, but the value is unexpectedly a tuple, e.g.:

    def foo(x):
        return "Hi %s\n" % x

    The example shows you can pass in foo("foo") or foo(3) fine, but if you pass in foo((1,2)), it raises a TypeError. You should use this instead:

    def foo(x):
        return "Hi %s\n" % (x,)

    For logging, should not use:

    logging.debug('Hi %s' % msg)

    Use this instead:

    logging.debug('Hi %s', msg)
  • Avoid using '': it's ugly. For long lines, use this:

    long_line = ('first part '
                 'send part')
  • Put license information in a separate 'LICENSE' file: easy to update and keep the source file cleaner.

  • Use lower case plus '_' for module file name.

  • Don't split a file at first: do it until needed.

  • A good example to split a module file: first keep everything in modulename.py, then split it into:

    modulename
    |-- __init__.py
    |-- base.py
    `-- other.py

    And import everything to __init__.py. So other code doesn't need to change.

  • Never do:

    try:
        ...
    except:
        ...

    Instead, you can do:

    try:
        ...
    except Exception:
        ...

Reference:

Java

None: CodingStyle (last edited 2011-07-05 04:39:22 by ZhigangWang)