gpt4 book ai didi

python - 模块公开导入的包

转载 作者:行者123 更新时间:2023-11-28 17:44:47 24 4
gpt4 key购买 nike

我有一个模块:

test
__init__.py

__init__.py 我有一行:

import numpy as np

我想在我想创建的包(模块和子模块)中使用 numpy。

问题是,不知何故 numpy 暴露了。如果我运行 IPython 并执行

import test

将有一个 test.np 可访问。

我查看了 github 上的许多包,它们经常在主 __init__.py(sys、division 等)中导入很多包,但是当我在 IPython 中导入这些包时,没有任何外部模块被暴露。

他们有什么不同之处?

最佳答案

您可以定义一个全局名称 __all__,设置为名称的列表或元组,以限制导入的内容以及通常将列出的文档工具:

__all__ = ['function1', 'ClassName2']

__all__ 名称限制了 from test import * 将导入的内容,文档工具也使用它来限制列为给定模块的公共(public) API 的内容。

参见 import statement文档:

The public names defined by a module are determined by checking the module’s namespace for a variable named __all__; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in __all__ are all considered public and are required to exist. If __all__ is not defined, the set of public names includes all names found in the module’s namespace which do not begin with an underscore character ('_'). __all__ should contain the entire public API. It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module).

您检查的 __init__ 模块几乎肯定会定义 __all__ 序列。

你也可以从你的模块中再次删除名称,前提是你的函数以后不需要访问全局名称:

del sys

否则,IPython 自动完成会使用所有 不以下划线开头的名称;自动完成会忽略 __all__ 列表,但会忽略像 _sys 这样的名称。

numpy.__init__ module (在 1.8.0 版本之前)本身再次从全局命名空间中删除名称:

if __NUMPY_SETUP__:
import sys as _sys
_sys.stderr.write('Running from numpy source directory.\n')
del _sys

但这里 sys 被绑定(bind)为 _sys 并且 IPython 会忽略该名称,即使它没有被删除。 numpy 还在该模块中构建了一个 __all__ 列表。

numpy 1.8.0 及更新版本中,一个 import sys 语句被添加到该文件并且 IPython 提供它用于自动完成,因为它仍然是全局的一部分命名空间。

关于python - 模块公开导入的包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19989179/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com