build details

Show: section status errors & todos local changes recent changes last change in-page changes feedback controls

Basic Python code conventions

Modified 2019-09-22 by Andrea Censi

How to write Python code that looks like Python code

The Black Python formatter

Modified 2019-09-22 by Andrea Censi

You should use black, the standard Python formatter, which will make your code look like anyone else’s code.

Tabs, spaces, indentation

Modified 2019-09-22 by Andrea Censi

Indentation is 4 spaces.

Never use tabs in Python files. The tab characters are evil.

If you find pre-existing code that uses tabs, be very careful in changing them. Do not use a tool to do it (e.g. “Convert tabs to spaces”); it will get it wrong.

Line lengths

Modified 2019-09-22 by Andrea Censi

Lines should be below 85 characters.

Long lines are a symptom of a bigger problem. The problem here is that you do not know how to program well, therefore you create programs with longer lines.

Do not go and try to shorten the lines; the line length is just the symptom. Rather, ask somebody to take a look at the code and tell you how to make it better.

The encoding line

Modified 2019-09-22 by Andrea Censi

All files must have an encoding declared, and this encoding must be utf-8:

# -*- coding: utf-8 -*-

Sha-bang lines

Modified 2019-09-22 by Andrea Censi

Executable files start with:

#!/usr/bin/env python

Comments

Modified 2019-09-22 by Andrea Censi

Comments refer to the next line.

Comments, bad:

from std_msgs.msg import String # This is my long comment

Comments, better:

# This is my long comment
from std_msgs.msg import String

Imports

Modified 2019-09-22 by Andrea Censi

Do not do a star import, like the following:

from rostest_example.Quacker import *

Rather, import each symbol by name:

from rostest_example.Quacker import MySymbol, Another

Logging

Modified 2019-09-22 by Andrea Censi

Do not use print for logging.

Rather, use the logging library:

# initialize the logger
import logging
logger = logging.getLogger('my program')
logger.setLevel(logging.DEBUG)

# then, later
logging.info("info message")
logging.error("error message")
logging.warning("warning message")

Exceptions

Modified 2019-09-22 by Andrea Censi

Exceptions are good. Throw them all the time! You will regret if you don’t.

Get in the habit of catching and re-raising using the from keyword:

try:
    some_function()
except BaseException as e:
    msg = 'Some function failed while I was doing this thing.'
    raise Exception(msg) from e

Python will show the full stack trace, telling you what exception caused what other.

sys.exit

Modified 2019-09-22 by Andrea Censi

It is extremely rare that calling sys.exit is the right thing to do. You should use exceptions instead.