Richard Jones' Log: Python module statement ordering ... wart?

Thu, 14 Jan 2010

Can't call this one a "wart" because it's present in Python 3 and we all know Python 3 got rid of all the warts <wink>.

It has to do with the very specific ordering of statements at the top of your Python source. Specifically if you have any of the following they must appear in this order:

  1. Top-of-file comments (Typically "# /usr/bin/env python", file encoding or source control revision ID string), then
  2. Module documentation string, then
  3. "from __future__ import ..." statement(s), then
  4. The rest of your module.

Failure to order them precisely like this will result in one of a couple of things: either your docstring will not be created correctly (as the __doc__ attribute) or you'll get a SyntaxError because your "from __future__ import ..." statements aren't "at the beginning of the file" (even though they can't be at the beginning of the file.) If the docstring appears after the "from __future__" imports it won't be used as __doc__.