Search code examples
pythonpypipython-packaging

python package best practice: managing imports


Coming from R, I'm trying to wrap my head around the package system in python.

My question (in short) is: what is the best practice for managing external library imports?

Suppose I have a package (call it pointless) with the following directory structure.

pointless/
    setup.py
    ...etc
    pointless/
        __init__.py
        module1.py
        module2.py

And suppose both module1 and module2 had the header:

from __future__ import division
import numpy as np
...

My issue is that when I import pointless I get a double-whammy of np and division in both pointless.module1 and pointless.module2. There has to be a better way?

EDIT

Apologies if that wasn't clear. It bugs me that when I run (ipython):

>>> import pointless
>>> pointless.module1.<TAB>
pointless.module1.np
pointless.module.division
...

>>> pointless.module2.<TAB>
pointless.module1.np
pointless.module.division
...

I can see the np namespace in both modules, which seems messy and way overkill.

Is there a way I can "centralize" my external library imports so that I don't see them in every module? Or am I missing something?


Solution

  • This is related to this question: what happens when i import module twice in python. Long story short: If you import a module twice, it is loaded only once, so your example is not problematic at all.