将子模块函数导入父命名空间

时间:2017-04-14 14:43:42

标签: python optimization namespaces python-import directory-structure

我有一套常用的实用工具函数,我使用不同的部分导入到大量不同的项目中。 I'm following patterns that I've seen in numpy,通过以下方式执行:

utils/
    __init__.py
        ```
        from . import math
        from . import plot
        ```
    math/
        __init__.py
            ```
            from . import core
            from . core import *
            from . import stats
            from . stats import *
            __all__ = []
            __all__.extend(core.__all__)
            __all__.extend(stats.__all__)
            ```
        core.py
            ```
            __all__ = ['cfunc1', 'cfunc2']
            def cfunc1()...
            def cfunc2()...
            ```
        stats.py
            ```
            __all__ = ['sfunc1', 'sfunc2']
            def sfunc1()...
            def sfunc2()...
            ```
    plot/
        __init__.py

这个结构的好处是我可以从更高级别的命名空间调用子模块函数,例如utils.math.cfunc1()utils.math.sfunc2()。 问题是:corestats都需要很长时间才能导入,因此我不想从math.__init__自动导入它们。

默认情况下有没有办法导入statscore,而是使用类似import utils.math.core的内容,但仍然有core中的函数最终会出现在math命名空间中?即能够执行:

import utils.math.core
utils.math.cfunc1()

0 个答案:

没有答案