Imports in Packages

tjhnson at gmail.com tjhnson at gmail.com
Mon Dec 17 05:24:04 EST 2007


While working within a package...what is the 'best practice' way to do
your imports.

a/__init__.py
a/one.py
a/two.py
a/b/__init__.py
a/b/cat.py
a/b/dog.py
a/c/cow.py
Suppose I am working in a/c/cow.py and I need something from a/b/
dog.py.  If a/b/__init__.py contains what I need from dog.py, should I
do:

"from a.b import desiredfunction"

or

"from a.b.dog import desiredfunction"

What are your reasons for preferring one over the other (performance,
readability, portability)?  Also, the same can be said of functions
from other packages...

I know that

>>> from math import cos
>>> x = cos(3)

is preferred for performance reasons over

>>> import math
>>> x = math.cos(3)

because of the required lookup.  Does this mean that that I should
import as far down as possible as well?  For example, "from a.b.c.mod
import func"  versus  "from a import fun".



More information about the Python-list mailing list