简体   繁体   English

python包最佳实践:管理导入

[英]python package best practice: managing imports

Coming from R, I'm trying to wrap my head around the package system in python. 来自R,我正在尝试用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 )。

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

And suppose both module1 and module2 had the header: 并假设module1module2都有标头:

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 . 我的问题是,当我import pointless时,我在pointless.module1pointless.module2中都得到了npdivision的双重打击。 There has to be a better way? 一定有更好的方法?

EDIT 编辑

Apologies if that wasn't clear. 抱歉,如果不清楚。 It bugs me that when I run (ipython): 当我运行(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. 我可以在两个模块中看到np命名空间,这看起来很杂乱,而且方法过于简单。

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 . 这与以下问题有关: 当我在python中两次导入模块时会发生什么 Long story short: If you import a module twice, it is loaded only once, so your example is not problematic at all. 长话短说:如果您两次导入一个模块,那么它只会被加载一次,因此您的示例完全没有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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