Imports in Packages
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Mon Dec 17 16:26:31 EST 2007
tjhnson at gmail.com 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
>
>
>>>>from math import cos
>>>>x = cos(3)
>
>
> is preferred for performance reasons over
>
>
>>>>import math
>>>>x = math.cos(3)
>
> 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.
More information about the Python-list
mailing list