Good practice when writing modules...

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Sat Nov 15 05:08:05 EST 2008


r0g:
> a) Import all the other modules these functions depend on into the
> modules global namespace by putting them at the top of the module or
> should I...
> b) Include them in each function individually.

This is a interesting topic, that requires some care.
Generally I suggest you put them at the top, so they can be found and
seen with less problems (*), it's the standard.
If a function is called only once in a while (like a plotting
function), and to import its module(s) it needs lot of time and memory
(like matplotlib), then you may move the import inside the function
itself, especially if such function isn't speed-critical.


(*)
I generally agree with the PEP8 but regarding this I don't follow it:
I feel free to put more than one of them on the same line:
import os, sys, ...
I generally list the built-in modules first, then the well known one
(pyparsing, numpy, etc), and then my ones or less known ones.

I also put a comment after each import, with the name of the function/
class it is used into:

import foo # used by baz()
import bar # used by spam()

...
def baz(n):
    return foo(n) * 10
...
def spam(k):
    return bar(k) - 20

Time ago I have read an interesting article that says that comments of
today will often become statements and declaration and tags of
tomorrow, that is stuff that the interpreter/compiler/editor
understands. This means that such annotations of mine may be something
fit to become a syntax of the language. I don't have ideas on how such
syntax can be, if you have suggestions I'm listening.

Finally in modules that contain many different things, and where each
of them uses generally distinct modules, as a compromise I sometimes
write code like this:

import foo # used by baz()

def baz(n):
    return foo(n) * 10


import bar # used by spam()

def spam(k):
    return bar(k) - 20

My editor has a command that finds and lists me all the global imports
(not indented) of the module.

Bye,
bearophile



More information about the Python-list mailing list