gpt4 book ai didi

python - 如何在不导入包含函数的文件的情况下将函数导入 Python 包?

转载 作者:行者123 更新时间:2023-11-28 21:51:11 25 4
gpt4 key购买 nike

我在 Mac OSX 上使用 Python 3.4.2 工作,我有一个简单的版本控制 Python 项目,其目录/文件结构如下所示:

vcs_projectname/
foo/
__init__.py
simplefunc.py
docs/
other_related_stuff/

__init__.py 文件如下所示:

from .simplefunc import helloworld
__all__ = ['helloworld'] # Not sure whether I really need this line...?

simplefunc.py 文件如下所示:

def helloworld():
print('Hello world!')

我通过更改到项目层次结构之外的目录来测试我的代码,将我的 PYTHONPATH 环境变量(在 bash 中)设置为指向 vcs_projectname 基本目录,并且发射 ipython :

> cd ~
> export PYTHONPATH=~/vcs_projectname
> ipython

在 ipython 中,我导入包 foo,然后查看其目录结构,结果如下:

In [1]: import foo

In [2]: dir(foo)
Out[2]:
['__all__',
'__builtins__',
'__cached__',
'__doc__',
'__file__',
'__loader__',
'__name__',
'__package__',
'__path__',
'__spec__',
'helloworld',
'simplefunc']

我的问题:如何去掉包目录结构中对 simplefunc 文件模块的引用?这样做是可取的,因为在最好的情况下它只是无用的困惑(我们在那里不需要它,因为我们真正想要的东西,helloworld() 函数,已经在__init__.py 文件的包级别),在最坏的情况下,它本质上是对不相关的实现细节(项目的底层文件结构)的引用,以后可能会更改,因此我不希望我的用户对 future 的版本产生期望和依赖。

最佳答案

您尝试做的事情不可能优雅地进行。正如@Lukas 所提到的,有一些技巧可以实现这一点。

相反,我一直在关注的是,创建一个名为 _private 的子包,并将所有此类模块放入其中。这样,当用户导入包时,所有公开的 API 都可用,私有(private) API 隐藏在 _private 中。

示例:

foo/
__init__.py
_private/
__init__.py
test1.py
test2.py

foo/__init__.py:

from _private import bar, baz

foo/_private/__init__.py:

from test1 import bar
from test2 import baz

foo/_private/test1.py:

def bar():
print "bar"

foo/_private/test2.py:

def baz():
print "baz"

导入foo:

>>> import foo
>>> dir(foo)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '_private', 'bar', 'baz']

关于python - 如何在不导入包含函数的文件的情况下将函数导入 Python 包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30673368/

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