Good practice when writing modules...

Nick Craig-Wood nick at craig-wood.com
Sun Nov 16 12:29:58 EST 2008


r0g <aioe.org at technicalbloke.com> wrote:
>  I'm collecting together a bunch of fairly random useful functions I have
>  written over the years into a module. Generally speaking is it best to
> 
>  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.
> 
>  Stylistically I like the idea of b) better as it makes for easy
>  refactoring in the future but is there any drawback to doing it this
>  way? i.e. does it get repeatedly parsed, use more memory, become
>  inefficient when several functions that use the same includes are
>  invoked etc Or does it really not matter?

b) has the disadvantage / possible advantage that if the module it
depends on isn't present then it doesn't complain until run time.  a)
will always complain at compile time (ie when the script is loaded).

I tend to put all my imports on the top, and I tend to write them like
this

from a_module import fn1, fn2, fn3

Which fails definitively at compile time rather than waiting for the
fn1() to be called.

Importing things into your local namespace is also the quickest, but
that isn't why I do it!

There are arguments against doing this, which I'm sure you'll hear
shortly ;-)

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list