python - 如何定义模块的导入?

标签 python python-3.x

我的目录结构是这样的:

└── stuff
    ├── __init__.py
    └── substuff
        ├── imp.py
        └── __init__.py

stuff/__init__.py 看起来如下:

from stuff.substuff.imp import foo, bar

stuff/substuff/__init__.py 像这样:

from stuff.substuff.imp import foo, bar

__all__ = [
    'foo',
    'bar'
]

stuff/substuff/imp.py 包含

import pandas as pd
import numpy as np

__all__ = ['foo', 'bar']


def foo():
    return {'foo': np.sqrt(2)}


def bar():
    return ('bar', 'xyz')


def _helper():
    return True

如果我现在做

from stuff.substuff import imp

并检查可用于 imp 的内容,我看到 barfoo,还有 pdnp.

我怎样才能让用户只看到barfoo,而看不到pdnp?一种解决方案似乎是将它们导入为 _pd_np,但我想知道是否有比这更“漂亮”的解决方案。

最佳答案

首先,请注意 __all__ 不会阻止任何模块符号(函数、类等)被直接导入。检查这个惊人的 article更多细节。它只为 from stuff.substuff.imp import * 设置行为,而不是显式模块导入(docs)。

这个语句只会像你期望的那样导入 foobar:

from stuff.substuff import *

此外,您已经限制了直接从 substuff 包导入到 foobar:

from stuff.substuff import foo  # successfully imported
from stuff.substuff import pd  # import error

关于python - 如何定义模块的导入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57132688/

相关文章:

python - 如何在同一行打印两个列表中的项目?

python - 在 Python 正则表达式中指定匹配新行的不同方法

python - 多行正则表达式与迭代器兼容吗?

python - 在给定条件下替换 Pandas 系列中的值

python - 如何将 ODE 系统与 FEM 系统相结合

python - 如何在 Python 2.7 中映射键盘按键?

python - 更改 Python 中的全局变量

Python 应用程序因 "PyEval_RestoreThread: the function must be called with the GIL held, but the GIL is released"崩溃

python-3.x - Python 3.4 ssl.SSLEOFError : EOF occurred in violation of protocol (_ssl. c:1638)

python - 尝试从 Excel 中获取子集