handling modules in packages

Steve Holden steve at holdenweb.com
Wed Sep 5 09:42:58 EDT 2007


Tommy Grav wrote:
> Hi,
> 
>    I am working on a package that contains a number of
> different modules:
> 
>  > ls pyAstro
> __init__.py
> constants.py
> conversion.py
> observation.py
> orbit.py
> transformation.py
> 
> however, I find that several of the modules have the
> same import statements:
> 
> orbit.py:
> 
> import numpy
> import constants
> import conversion
> import observations
> 
> observations.py:
> 
> import numpy
> import constants
> import conversions
> import transformations
> 
> The modules themselves are not overly large, but it bugs
> me to have to import numpy twice (or even more as the
> number of modules grow). Is there a way to import numpy
> once in the package (like in the __init__.py file) such that
> it is accessible to all the modules? Or is the multiple imports
> just something one has to live with?
> 
> Thanks for any help or direction to webpages discussing this
> topic.
> 
> Cheers
>    Tommy
> 
The simplest thing to do would be to have PyAstro.__init__.py import all 
the sub-modules, and define __all__ as the set of names that the package 
should inject into importing modules.

Then you could write (for example)

from PyAstro import numpy, constants, conversion, obsrvations

However if you are simply worried about run-time efficiency then don't 
be: once a module is imported further imports essentially reduce to 
checking that the module is already present in the sys.modules dict, and 
so take almost no time at all.

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------




More information about the Python-list mailing list