简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM