Good practice when writing modules...

Arnaud Delobelle arnodel at googlemail.com
Sat Nov 15 04:03:15 EST 2008


r0g <aioe.org at technicalbloke.com> writes:

> 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?

I guess it costs you a dictionary lookup (in sys.modules) and an
assignment every time the import statement is executed.  But the module
is not reimported every time.

> Performance is probably not important for the majority of these
> functions but there's the odd one that may end up in an inner loop some day.

It depends on the function but unless it is a function with special
status (such as testing, or a main() function) I would import stuff at
the top of the module.  I makes it clear what the module depends on.

-- 
Arnaud



More information about the Python-list mailing list