Imports in Packages

T

tjhnson

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

is preferred for performance reasons over

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".
 
B

Bruno Desthuilliers

(e-mail address removed) a écrit :
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 would be the point of exposing desiredfunction in a/b/__init__ if
you still import it from a/b/dog ?-)
What are your reasons for preferring one over the other (performance,
readability, portability)?

What about encapsulation of the package's internal organisation ?

(snip)
I know that




is preferred for performance reasons over



because of the required lookup.

If you only use it once, it won't make such a difference wrt/ lookup
time. The "make names local" trick is mostly useful for tight loops in
functions. Else, better to go for readability and favor the first form
IMHO - at least you don't wonder where this 'cos' stuff come from !-)
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".

This won't save anything wrt/ lookup. And I stronly suggest that you
read more about namespaces and lookup rules in Python.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top